text
stringlengths 30
1.67M
|
|---|
<s> package org . eclim . installer . step ; import java . io . File ; import java . io . FilenameFilter ; import org . apache . commons . io . FilenameUtils ; import org . formic . Installer ; public class EclipseUtils { private static final String LAUNCHER_PREFIX = "<STR_LIT>" ; public static String findEclipseLauncherJar ( ) { String eclipseHome = Installer . getProject ( ) . getProperty ( "<STR_LIT>" ) ; if ( eclipseHome == null ) { return null ; } return findEclipseLauncherJar ( eclipseHome ) ; } public static String findEclipseLauncherJar ( String eclipseHome ) { String plugins = eclipseHome + "<STR_LIT>" ; String [ ] results = new File ( plugins ) . list ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . startsWith ( LAUNCHER_PREFIX ) && name . endsWith ( "<STR_LIT>" ) ; } } ) ; if ( results != null && results . length > <NUM_LIT:0> ) { return FilenameUtils . concat ( plugins , results [ <NUM_LIT:0> ] ) ; } return null ; } } </s>
|
<s> package org . eclim . installer . step ; import java . io . File ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; public class Feature { public static final Pattern VERSION = Pattern . compile ( "<STR_LIT>" ) ; private String version ; private File site ; public Feature ( String version , File site ) { this . site = site ; Matcher matcher = VERSION . matcher ( version ) ; matcher . find ( ) ; this . version = matcher . group ( <NUM_LIT:1> ) ; } public String getVersion ( ) { return version ; } public File getSite ( ) { return this . site ; } } </s>
|
<s> package org . eclim . installer . step ; import java . beans . PropertyChangeEvent ; import java . beans . PropertyChangeListener ; import java . io . File ; import org . formic . Installer ; import org . formic . wizard . step . shared . Feature ; public class FeatureProvider implements org . formic . wizard . step . shared . FeatureProvider , PropertyChangeListener { public static final String [ ] FEATURES = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; private static final String [ ] [ ] FEATURES_DEPENDS = { null , { "<STR_LIT>" , "<STR_LIT>" } , null , null , null , { "<STR_LIT>" } , { "<STR_LIT>" , "<STR_LIT>" } , null } ; public Feature [ ] getFeatures ( ) { EclipseInfo info = ( EclipseInfo ) Installer . getContext ( ) . getValue ( "<STR_LIT>" ) ; boolean [ ] enabled = new boolean [ FEATURES . length ] ; for ( int ii = <NUM_LIT:0> ; ii < FEATURES . length ; ii ++ ) { enabled [ ii ] = false ; if ( FEATURES [ ii ] . equals ( "<STR_LIT>" ) ) { String path = Installer . getProject ( ) . replaceProperties ( "<STR_LIT>" ) ; enabled [ ii ] = new File ( path ) . exists ( ) ; continue ; } else { enabled [ ii ] = info . getUninstalledDependencies ( FEATURES [ ii ] ) . size ( ) == <NUM_LIT:0> ; } } Feature [ ] features = new Feature [ FEATURES . length ] ; for ( int ii = <NUM_LIT:0> ; ii < features . length ; ii ++ ) { features [ ii ] = new Feature ( FEATURES [ ii ] , enabled [ ii ] , FEATURES_DEPENDS [ ii ] ) ; } return features ; } public void propertyChange ( PropertyChangeEvent evt ) { } } </s>
|
<s> package org . eclim . installer . step ; import java . awt . BorderLayout ; import java . awt . Color ; import java . awt . Component ; import java . awt . Dimension ; import java . awt . FlowLayout ; import java . awt . event . ActionEvent ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Comparator ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import javax . swing . AbstractAction ; import javax . swing . BorderFactory ; import javax . swing . BoxLayout ; import javax . swing . ImageIcon ; import javax . swing . JButton ; import javax . swing . JLabel ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JTable ; import javax . swing . ListSelectionModel ; import javax . swing . SwingUtilities ; import javax . swing . event . ListSelectionEvent ; import javax . swing . event . ListSelectionListener ; import javax . swing . table . DefaultTableCellRenderer ; import javax . swing . table . DefaultTableModel ; import org . apache . commons . io . FilenameUtils ; import org . apache . commons . lang . StringUtils ; import org . apache . commons . lang . SystemUtils ; import org . eclim . installer . step . command . Command ; import org . eclim . installer . step . command . InstallCommand ; import org . eclim . installer . step . command . ListCommand ; import org . eclim . installer . step . command . OutputHandler ; import org . eclim . installer . theme . DesertBlue ; import org . formic . Installer ; import org . formic . util . dialog . gui . GuiDialogs ; import org . formic . wizard . step . gui . InstallStep ; import com . jgoodies . looks . plastic . PlasticTheme ; import foxtrot . Worker ; public class EclipsePluginsStep extends InstallStep implements OutputHandler { private static final String BEGIN_TASK = "<STR_LIT>" ; private static final String PREPARE_TASK = "<STR_LIT>" ; private static final String SUB_TASK = "<STR_LIT>" ; private static final String INTERNAL_WORKED = "<STR_LIT>" ; private static final String SET_TASK_NAME = "<STR_LIT>" ; private static final Color ERROR_COLOR = new Color ( <NUM_LIT:255> , <NUM_LIT> , <NUM_LIT> ) ; private String taskName = "<STR_LIT>" ; private JPanel stepPanel ; private JPanel featuresPanel ; private JLabel messageLabel ; private ImageIcon errorIcon ; private DefaultTableModel tableModel ; private List < Dependency > dependencies ; private Map < String , String > availableFeatures ; private PlasticTheme theme ; private int overallProgressStep ; public EclipsePluginsStep ( String name , Properties properties ) { super ( name , properties ) ; } public Component init ( ) { theme = new DesertBlue ( ) ; stepPanel = ( JPanel ) super . init ( ) ; stepPanel . setBorder ( null ) ; JPanel panel = new JPanel ( ) ; panel . setLayout ( new BoxLayout ( panel , BoxLayout . PAGE_AXIS ) ) ; messageLabel = new JLabel ( ) ; messageLabel . setPreferredSize ( new Dimension ( <NUM_LIT> , <NUM_LIT> ) ) ; panel . add ( messageLabel ) ; panel . add ( stepPanel ) ; panel . setBorder ( BorderFactory . createEmptyBorder ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT:10> , <NUM_LIT> ) ) ; return panel ; } private void setMessage ( String message ) { if ( errorIcon == null ) { errorIcon = new ImageIcon ( Installer . getImage ( "<STR_LIT>" ) ) ; } if ( message != null ) { messageLabel . setIcon ( errorIcon ) ; messageLabel . setText ( message ) ; } else { messageLabel . setIcon ( null ) ; messageLabel . setText ( null ) ; } } public void displayed ( ) { setBusy ( true ) ; setPreviousEnabled ( false ) ; try { overallLabel . setText ( "<STR_LIT>" ) ; overallProgress . setValue ( <NUM_LIT:0> ) ; taskLabel . setText ( "<STR_LIT>" ) ; taskProgress . setValue ( <NUM_LIT:0> ) ; taskProgress . setIndeterminate ( true ) ; if ( featuresPanel != null ) { stepPanel . remove ( featuresPanel ) ; } EclipseInfo info = ( EclipseInfo ) Installer . getContext ( ) . getValue ( "<STR_LIT>" ) ; dependencies = unsatisfiedDependencies ( info ) ; if ( dependencies . size ( ) == <NUM_LIT:0> ) { overallProgress . setMaximum ( <NUM_LIT:1> ) ; overallProgress . setValue ( <NUM_LIT:1> ) ; overallLabel . setText ( "<STR_LIT>" ) ; taskProgress . setMaximum ( <NUM_LIT:1> ) ; taskProgress . setValue ( <NUM_LIT:1> ) ; taskLabel . setText ( "<STR_LIT>" ) ; } else { tableModel = new DefaultTableModel ( ) ; tableModel . addColumn ( "<STR_LIT>" ) ; tableModel . addColumn ( "<STR_LIT>" ) ; tableModel . addColumn ( "<STR_LIT>" ) ; JTable table = new JTable ( tableModel ) ; table . setSelectionMode ( ListSelectionModel . SINGLE_SELECTION ) ; table . setDefaultRenderer ( Object . class , new DependencyCellRenderer ( ) ) ; table . getSelectionModel ( ) . addListSelectionListener ( new DependencySelectionListener ( ) ) ; featuresPanel = new JPanel ( new BorderLayout ( ) ) ; featuresPanel . setAlignmentX ( <NUM_LIT:0.0f> ) ; JPanel container = new JPanel ( new BorderLayout ( ) ) ; container . add ( table , BorderLayout . CENTER ) ; JScrollPane scrollPane = new JScrollPane ( container ) ; scrollPane . setAlignmentX ( <NUM_LIT:0.0f> ) ; availableFeatures = loadAvailableFeatures ( ) ; for ( Dependency dependency : dependencies ) { String version = availableFeatures . get ( dependency . getId ( ) ) ; String manual = "<STR_LIT>" ; if ( version == null ) { manual = "<STR_LIT>" ; version = dependency . getRequiredVersion ( ) ; } tableModel . addRow ( new Object [ ] { dependency . getId ( ) , version , ( dependency . isUpgrade ( ) ? "<STR_LIT>" : "<STR_LIT>" ) + manual , } ) ; } JPanel buttons = new JPanel ( new FlowLayout ( FlowLayout . RIGHT , <NUM_LIT:0> , <NUM_LIT:0> ) ) ; buttons . setAlignmentX ( <NUM_LIT:0.0f> ) ; JButton skipButton = new JButton ( new SkipPluginsAction ( ) ) ; JButton installButton = new JButton ( new InstallPluginsAction ( skipButton ) ) ; buttons . add ( installButton ) ; buttons . add ( skipButton ) ; featuresPanel . add ( scrollPane , BorderLayout . CENTER ) ; featuresPanel . add ( buttons , BorderLayout . SOUTH ) ; stepPanel . add ( featuresPanel ) ; overallProgress . setValue ( <NUM_LIT:0> ) ; overallLabel . setText ( "<STR_LIT>" ) ; taskProgress . setValue ( <NUM_LIT:0> ) ; taskLabel . setText ( "<STR_LIT>" ) ; } } catch ( Exception e ) { setError ( e ) ; } finally { setValid ( dependencies != null && dependencies . size ( ) == <NUM_LIT:0> ) ; setBusy ( false ) ; setPreviousEnabled ( true ) ; taskProgress . setIndeterminate ( false ) ; } } public void process ( final String line ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { if ( line . startsWith ( BEGIN_TASK ) ) { String l = line . substring ( BEGIN_TASK . length ( ) + <NUM_LIT:2> ) ; double work = Double . parseDouble ( l . substring ( l . indexOf ( '<CHAR_LIT:=>' ) + <NUM_LIT:1> , l . indexOf ( '<CHAR_LIT:U+0020>' ) ) ) ; taskProgress . setIndeterminate ( false ) ; taskProgress . setMaximum ( ( int ) work ) ; taskProgress . setValue ( <NUM_LIT:0> ) ; } else if ( line . startsWith ( PREPARE_TASK ) ) { taskLabel . setText ( line . substring ( PREPARE_TASK . length ( ) + <NUM_LIT:1> ) . trim ( ) ) ; } else if ( line . startsWith ( SUB_TASK ) ) { taskLabel . setText ( taskName + line . substring ( SUB_TASK . length ( ) + <NUM_LIT:1> ) . trim ( ) ) ; } else if ( line . startsWith ( INTERNAL_WORKED ) ) { double worked = Double . parseDouble ( line . substring ( INTERNAL_WORKED . length ( ) + <NUM_LIT:2> ) ) ; taskProgress . setValue ( ( int ) worked ) ; overallProgress . setValue ( overallProgressStep + ( int ) ( taskProgress . getPercentComplete ( ) * <NUM_LIT:100> ) ) ; } else if ( line . startsWith ( SET_TASK_NAME ) ) { taskName = line . substring ( SET_TASK_NAME . length ( ) + <NUM_LIT:1> ) . trim ( ) + '<CHAR_LIT:U+0020>' ; } } } ) ; } private List < Dependency > unsatisfiedDependencies ( EclipseInfo info ) { List < Dependency > deps = new ArrayList < Dependency > ( ) ; String [ ] features = Installer . getContext ( ) . getKeysByPrefix ( "<STR_LIT>" ) ; Arrays . sort ( features , new FeatureNameComparator ( ) ) ; for ( int ii = <NUM_LIT:0> ; ii < features . length ; ii ++ ) { Boolean enabled = ( Boolean ) Installer . getContext ( ) . getValue ( features [ ii ] ) ; if ( enabled . booleanValue ( ) ) { String name = features [ ii ] . substring ( features [ ii ] . indexOf ( '<CHAR_LIT:.>' ) + <NUM_LIT:1> ) ; deps . addAll ( info . getUnsatisfiedDependencies ( name ) ) ; } } return deps ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) private Map < String , String > loadAvailableFeatures ( ) throws Exception { overallProgress . setMaximum ( <NUM_LIT:1> ) ; overallLabel . setText ( "<STR_LIT>" ) ; return ( Map < String , String > ) Worker . post ( new foxtrot . Task ( ) { public Object run ( ) throws Exception { ArrayList < String > sites = new ArrayList < String > ( ) ; for ( Dependency dependency : dependencies ) { if ( ! sites . contains ( dependency . getSite ( ) ) ) { sites . add ( dependency . getSite ( ) ) ; } } final Map < String , String > availableFeatures = new HashMap < String , String > ( ) ; OutputHandler handler = new OutputHandler ( ) { public void process ( String line ) { String [ ] parts = StringUtils . split ( line , "<STR_LIT:=>" ) ; if ( parts . length == <NUM_LIT:2> && parts [ <NUM_LIT:0> ] . endsWith ( "<STR_LIT>" ) ) { availableFeatures . put ( parts [ <NUM_LIT:0> ] . replace ( "<STR_LIT>" , "<STR_LIT>" ) , parts [ <NUM_LIT:1> ] ) ; } } } ; Command command = new ListCommand ( handler , sites . toArray ( new String [ sites . size ( ) ] ) ) ; try { command . start ( ) ; command . join ( ) ; if ( command . getReturnCode ( ) != <NUM_LIT:0> ) { throw new RuntimeException ( "<STR_LIT>" + command . getErrorMessage ( ) + "<STR_LIT>" + command . getResult ( ) ) ; } } finally { command . destroy ( ) ; } return availableFeatures ; } } ) ; } private class InstallPluginsAction extends AbstractAction { private static final long serialVersionUID = <NUM_LIT:1L> ; private JButton skipButton ; public InstallPluginsAction ( JButton skipButton ) { super ( "<STR_LIT>" ) ; this . skipButton = skipButton ; } public void actionPerformed ( ActionEvent e ) { ( ( JButton ) e . getSource ( ) ) . setEnabled ( false ) ; setPreviousEnabled ( true ) ; try { Boolean successful = ( Boolean ) Worker . post ( new foxtrot . Task ( ) { public Object run ( ) throws Exception { for ( Dependency dependency : dependencies ) { Feature feature = dependency . getFeature ( ) ; if ( feature != null ) { if ( feature . getSite ( ) == null ) { String installLog = FilenameUtils . concat ( SystemUtils . JAVA_IO_TMPDIR , "<STR_LIT>" ) ; GuiDialogs . showWarning ( Installer . getString ( "<STR_LIT>" , installLog ) ) ; return Boolean . FALSE ; } else if ( ! feature . getSite ( ) . canWrite ( ) ) { GuiDialogs . showWarning ( Installer . getString ( "<STR_LIT>" ) ) ; return Boolean . FALSE ; } } } overallProgress . setMaximum ( dependencies . size ( ) * <NUM_LIT:100> ) ; overallProgress . setValue ( <NUM_LIT:0> ) ; int removeIndex = <NUM_LIT:0> ; for ( Iterator < Dependency > ii = dependencies . iterator ( ) ; ii . hasNext ( ) ; ) { Dependency dependency = ii . next ( ) ; String version = availableFeatures . get ( dependency . getId ( ) ) ; if ( version != null ) { if ( ! dependency . isUpgrade ( ) ) { overallLabel . setText ( "<STR_LIT>" + dependency . getId ( ) + '<CHAR_LIT:->' + version ) ; } else { overallLabel . setText ( "<STR_LIT>" + dependency . getId ( ) + '<CHAR_LIT:->' + version ) ; } taskProgress . setValue ( <NUM_LIT:0> ) ; taskProgress . setIndeterminate ( true ) ; Command command = new InstallCommand ( EclipsePluginsStep . this , dependency . getSite ( ) , dependency . getId ( ) ) ; try { command . start ( ) ; command . join ( ) ; if ( command . getReturnCode ( ) != <NUM_LIT:0> ) { if ( command . isShutdown ( ) ) { return Boolean . TRUE ; } throw new RuntimeException ( "<STR_LIT>" + command . getErrorMessage ( ) + "<STR_LIT>" + command . getResult ( ) ) ; } } finally { command . destroy ( ) ; } ii . remove ( ) ; tableModel . removeRow ( removeIndex ) ; } else { removeIndex ++ ; } overallProgressStep += <NUM_LIT:100> ; overallProgress . setValue ( overallProgressStep ) ; } taskLabel . setText ( "<STR_LIT>" ) ; taskProgress . setValue ( taskProgress . getMaximum ( ) ) ; overallProgress . setValue ( overallProgress . getMaximum ( ) ) ; if ( dependencies . size ( ) > <NUM_LIT:0> ) { GuiDialogs . showWarning ( Installer . getString ( "<STR_LIT>" ) ) ; } return Boolean . TRUE ; } } ) ; if ( successful . booleanValue ( ) ) { overallProgress . setValue ( overallProgress . getMaximum ( ) ) ; overallLabel . setText ( Installer . getString ( "<STR_LIT>" ) ) ; taskProgress . setValue ( taskProgress . getMaximum ( ) ) ; taskLabel . setText ( Installer . getString ( "<STR_LIT>" ) ) ; setBusy ( false ) ; setValid ( true ) ; taskProgress . setIndeterminate ( false ) ; skipButton . setEnabled ( false ) ; } } catch ( Exception ex ) { setError ( ex ) ; } } } private class SkipPluginsAction extends AbstractAction { private static final long serialVersionUID = <NUM_LIT:1L> ; public SkipPluginsAction ( ) { super ( "<STR_LIT>" ) ; } public void actionPerformed ( ActionEvent e ) { if ( GuiDialogs . showConfirm ( Installer . getString ( "<STR_LIT>" ) ) ) { setValid ( true ) ; } } } private class DependencyCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = <NUM_LIT:1L> ; public Component getTableCellRendererComponent ( JTable table , Object value , boolean isSelected , boolean hasFocus , int row , int column ) { Component component = super . getTableCellRendererComponent ( table , value , isSelected , hasFocus , row , column ) ; Feature feature = ( ( Dependency ) dependencies . get ( row ) ) . getFeature ( ) ; if ( feature != null && ( feature . getSite ( ) == null || ! feature . getSite ( ) . canWrite ( ) ) ) { component . setBackground ( isSelected ? theme . getMenuItemSelectedBackground ( ) : ERROR_COLOR ) ; component . setForeground ( isSelected ? ERROR_COLOR : Color . BLACK ) ; } else { component . setBackground ( isSelected ? theme . getMenuItemSelectedBackground ( ) : Color . WHITE ) ; component . setForeground ( isSelected ? theme . getMenuItemSelectedForeground ( ) : theme . getMenuForeground ( ) ) ; } return component ; } } private class DependencySelectionListener implements ListSelectionListener { public void valueChanged ( ListSelectionEvent e ) { ListSelectionModel model = ( ListSelectionModel ) e . getSource ( ) ; int index = model . getMinSelectionIndex ( ) ; Feature feature = index >= <NUM_LIT:0> ? ( ( Dependency ) dependencies . get ( index ) ) . getFeature ( ) : null ; if ( feature != null ) { if ( feature . getSite ( ) == null ) { setMessage ( Installer . getString ( "<STR_LIT>" ) ) ; } else if ( ! feature . getSite ( ) . canWrite ( ) ) { setMessage ( Installer . getString ( "<STR_LIT>" ) ) ; } } else { setMessage ( null ) ; } } } private static class FeatureNameComparator implements Comparator < String > { private static ArrayList < String > NAMES = new ArrayList < String > ( ) ; static { NAMES . add ( "<STR_LIT>" ) ; NAMES . add ( "<STR_LIT>" ) ; NAMES . add ( "<STR_LIT>" ) ; NAMES . add ( "<STR_LIT>" ) ; NAMES . add ( "<STR_LIT>" ) ; NAMES . add ( "<STR_LIT>" ) ; } public int compare ( String ob1 , String ob2 ) { return NAMES . indexOf ( ob1 ) - NAMES . indexOf ( ob2 ) ; } } } </s>
|
<s> package org . eclim . installer . step . command ; public class InfoCommand extends Command { public InfoCommand ( OutputHandler handler ) { super ( handler , new String [ ] { "<STR_LIT>" } ) ; } } </s>
|
<s> package org . eclim . installer . step . command ; public class InstallCommand extends Command { public InstallCommand ( OutputHandler handler , String url , String id ) { this ( handler , url , id , "<STR_LIT>" ) ; } public InstallCommand ( OutputHandler handler , String url , String id , String application ) { super ( handler , new String [ ] { "<STR_LIT>" , url , "<STR_LIT>" , id + "<STR_LIT>" , } , application ) ; } } </s>
|
<s> package org . eclim . installer . step . command ; public class UninstallCommand extends Command { public UninstallCommand ( OutputHandler handler , String url , String id ) { this ( handler , url , id , "<STR_LIT>" ) ; } public UninstallCommand ( OutputHandler handler , String url , String id , String application ) { super ( handler , url != null ? new String [ ] { "<STR_LIT>" , url , "<STR_LIT>" , id + "<STR_LIT>" } : new String [ ] { "<STR_LIT>" , id + "<STR_LIT>" } , application ) ; } } </s>
|
<s> package org . eclim . installer . step . command ; public interface OutputHandler { public void process ( String line ) ; } </s>
|
<s> package org . eclim . installer . step . command ; import org . apache . commons . lang . StringUtils ; public class ListCommand extends Command { public ListCommand ( OutputHandler handler , String [ ] sites ) { super ( handler , new String [ ] { "<STR_LIT>" , StringUtils . join ( sites , '<CHAR_LIT:U+002C>' ) , "<STR_LIT>" , } , "<STR_LIT>" ) ; } } </s>
|
<s> package org . eclim . installer . step . command ; import java . io . BufferedReader ; import java . io . InputStreamReader ; import java . io . OutputStream ; import java . util . ArrayList ; import java . util . Map ; import java . util . regex . Pattern ; import org . eclim . installer . step . EclipseUtils ; import org . formic . Installer ; import org . formic . util . CommandExecutor ; public class Command extends CommandExecutor { private static final String [ ] LAUNCHER = new String [ ] { "<STR_LIT>" , null , "<STR_LIT>" , "<STR_LIT>" , null , } ; private static final Pattern PROPERTY_RE = Pattern . compile ( "<STR_LIT>" ) ; private OutputHandler handler ; public Command ( OutputHandler handler , String [ ] cmd ) { this ( handler , cmd , "<STR_LIT>" ) ; } public Command ( OutputHandler handler , String [ ] cmd , String application ) { String [ ] jargs = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; String [ ] vmargs = getJvmArgs ( ) ; this . handler = handler ; this . cmd = new String [ jargs . length + vmargs . length + cmd . length + LAUNCHER . length ] ; String launcher = EclipseUtils . findEclipseLauncherJar ( ) ; if ( launcher == null ) { throw new RuntimeException ( "<STR_LIT>" + Installer . getProject ( ) . getProperty ( "<STR_LIT>" ) ) ; } int index = <NUM_LIT:0> ; System . arraycopy ( jargs , <NUM_LIT:0> , this . cmd , index , jargs . length ) ; index += jargs . length ; System . arraycopy ( vmargs , <NUM_LIT:0> , this . cmd , index , vmargs . length ) ; index += vmargs . length ; System . arraycopy ( LAUNCHER , <NUM_LIT:0> , this . cmd , index , LAUNCHER . length ) ; index += LAUNCHER . length ; this . cmd [ jargs . length + vmargs . length + <NUM_LIT:1> ] = launcher ; this . cmd [ jargs . length + vmargs . length + <NUM_LIT:4> ] = application ; System . arraycopy ( cmd , <NUM_LIT:0> , this . cmd , index , cmd . length ) ; } @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) protected String [ ] getJvmArgs ( ) { ArrayList < String > vmargs = new ArrayList < String > ( ) ; for ( Map . Entry entry : System . getProperties ( ) . entrySet ( ) ) { String name = ( String ) entry . getKey ( ) ; if ( PROPERTY_RE . matcher ( name ) . matches ( ) ) { String value = ( String ) entry . getValue ( ) ; if ( value . length ( ) > <NUM_LIT:0> ) { vmargs . add ( "<STR_LIT>" + name + '<CHAR_LIT:=>' + entry . getValue ( ) ) ; } else { vmargs . add ( "<STR_LIT>" + name ) ; } } } return vmargs . toArray ( new String [ vmargs . size ( ) ] ) ; } protected Thread createOutThread ( final OutputStream out ) { return new Thread ( ) { public void run ( ) { StringBuffer buffer = new StringBuffer ( ) ; try { BufferedReader reader = new BufferedReader ( new InputStreamReader ( process . getInputStream ( ) ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { if ( buffer . length ( ) != <NUM_LIT:0> ) { buffer . append ( '<STR_LIT:\n>' ) ; } buffer . append ( line ) ; if ( handler != null ) { handler . process ( line ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; error = e . getMessage ( ) ; returnCode = <NUM_LIT:1000> ; process . destroy ( ) ; } finally { result = buffer . toString ( ) ; } } } ; } } </s>
|
<s> package org . eclim . installer . step ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileReader ; import java . io . FilenameFilter ; import java . util . ArrayList ; import java . util . Collections ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . apache . commons . io . IOUtils ; import org . apache . commons . lang . StringUtils ; import org . apache . tools . ant . taskdefs . condition . Os ; import org . formic . InstallContext ; import org . formic . Installer ; import org . formic . util . CommandExecutor ; import org . formic . wizard . step . gui . RequirementsValidationStep ; import org . formic . wizard . step . gui . RequirementsValidationStep . * ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class RequirementProvider implements RequirementsValidationStep . RequirementProvider { private static final Logger logger = LoggerFactory . getLogger ( RequirementProvider . class ) ; public Requirement [ ] getRequirements ( ) { if ( Os . isFamily ( "<STR_LIT>" ) ) { Requirement [ ] requirements = new Requirement [ <NUM_LIT:1> ] ; requirements [ <NUM_LIT:0> ] = new EclipseRequirement ( ) ; return requirements ; } InstallContext context = Installer . getContext ( ) ; boolean skipVim = ( ( Boolean ) context . getValue ( "<STR_LIT>" ) ) . booleanValue ( ) ; Requirement [ ] requirements = new Requirement [ skipVim ? <NUM_LIT:3> : <NUM_LIT:4> ] ; requirements [ <NUM_LIT:0> ] = new EclipseRequirement ( ) ; requirements [ <NUM_LIT:1> ] = new WhichRequirement ( "<STR_LIT>" ) ; requirements [ <NUM_LIT:2> ] = new WhichRequirement ( "<STR_LIT>" ) ; if ( ! skipVim ) { requirements [ <NUM_LIT:3> ] = new VimRequirement ( ) ; } return requirements ; } public Status validate ( Requirement requirement ) { ValidatingRequirement req = ( ValidatingRequirement ) requirement ; return req . validate ( ) ; } private class EclipseRequirement extends ValidatingRequirement { private final Pattern VERSION = Pattern . compile ( "<STR_LIT>" ) ; public EclipseRequirement ( ) { super ( "<STR_LIT>" ) ; } public Status validate ( ) { String eclipseHome = ( String ) Installer . getContext ( ) . getValue ( "<STR_LIT>" ) ; eclipseHome = eclipseHome . replace ( '<STR_LIT:\\>' , '<CHAR_LIT:/>' ) ; File file = new File ( eclipseHome + "<STR_LIT>" ) ; String version = null ; if ( file . exists ( ) ) { version = versionFromReadme ( file ) ; } if ( version == null ) { version = versionFromPlugins ( eclipseHome ) ; } if ( version == null ) { return new Status ( WARN , Installer . getString ( "<STR_LIT>" ) ) ; } String [ ] parts = StringUtils . split ( version , '<CHAR_LIT:.>' ) ; int major = Integer . parseInt ( parts [ <NUM_LIT:0> ] ) ; int minor = Integer . parseInt ( parts [ <NUM_LIT:1> ] ) ; int patch = parts . length > <NUM_LIT:2> ? Integer . parseInt ( parts [ <NUM_LIT:2> ] ) : <NUM_LIT:0> ; if ( major != <NUM_LIT:4> || minor < <NUM_LIT:2> || patch < <NUM_LIT:0> ) { return new Status ( FAIL , Installer . getString ( "<STR_LIT>" , version , "<STR_LIT>" ) ) ; } return OK_STATUS ; } public String versionFromReadme ( File file ) { BufferedReader reader = null ; try { reader = new BufferedReader ( new FileReader ( file ) ) ; String line = null ; for ( int ii = <NUM_LIT:0> ; ii < <NUM_LIT:30> ; ii ++ ) { line = reader . readLine ( ) ; Matcher matcher = VERSION . matcher ( line ) ; if ( matcher . matches ( ) ) { return matcher . group ( <NUM_LIT:1> ) ; } } } catch ( Exception e ) { logger . error ( "<STR_LIT>" , e ) ; } finally { IOUtils . closeQuietly ( reader ) ; } logger . warn ( "<STR_LIT>" , file ) ; return null ; } public String versionFromPlugins ( String eclipseHome ) { final String [ ] plugins = { "<STR_LIT>" } ; File file = new File ( eclipseHome + "<STR_LIT>" ) ; String [ ] names = file . list ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { for ( int ii = <NUM_LIT:0> ; ii < plugins . length ; ii ++ ) { if ( name . contains ( plugins [ ii ] ) ) { return true ; } } return false ; } } ) ; ArrayList < String > versions = new ArrayList < String > ( ) ; for ( int ii = <NUM_LIT:0> ; ii < names . length ; ii ++ ) { String version = names [ ii ] ; version = version . replaceFirst ( "<STR_LIT>" , "<STR_LIT>" ) ; version = version . replaceFirst ( "<STR_LIT>" , "<STR_LIT>" ) ; versions . add ( version ) ; } if ( versions . size ( ) > <NUM_LIT:0> ) { Collections . sort ( versions ) ; return versions . get ( versions . size ( ) - <NUM_LIT:1> ) ; } logger . warn ( "<STR_LIT>" ) ; return null ; } } private class VimRequirement extends ValidatingRequirement { private final Pattern VERSION = Pattern . compile ( "<STR_LIT>" ) ; public VimRequirement ( ) { super ( "<STR_LIT>" ) ; } public Status validate ( ) { try { CommandExecutor command = CommandExecutor . execute ( new String [ ] { "<STR_LIT>" , "<STR_LIT>" } , <NUM_LIT> ) ; if ( command . getReturnCode ( ) != <NUM_LIT:0> ) { logger . error ( "<STR_LIT>" , command . getErrorMessage ( ) ) ; return new Status ( WARN , Installer . getString ( "<STR_LIT>" ) ) ; } String result = command . getResult ( ) ; Matcher matcher = VERSION . matcher ( result ) ; if ( ! matcher . find ( ) ) { logger . error ( "<STR_LIT>" , result ) ; return new Status ( WARN , Installer . getString ( "<STR_LIT>" ) ) ; } String version = matcher . group ( <NUM_LIT:1> ) ; String [ ] parts = StringUtils . split ( version , '<CHAR_LIT:.>' ) ; int major = Integer . parseInt ( parts [ <NUM_LIT:0> ] ) ; int minor = Integer . parseInt ( parts [ <NUM_LIT:1> ] ) ; int patch = parts . length > <NUM_LIT:2> ? Integer . parseInt ( parts [ <NUM_LIT:2> ] ) : <NUM_LIT:0> ; if ( major < <NUM_LIT:7> || minor < <NUM_LIT:0> || patch < <NUM_LIT:0> ) { return new Status ( FAIL , Installer . getString ( "<STR_LIT>" , version , "<STR_LIT>" ) ) ; } } catch ( Exception e ) { logger . error ( "<STR_LIT>" , e ) ; return new Status ( WARN , Installer . getString ( "<STR_LIT>" ) ) ; } return OK_STATUS ; } } private class WhichRequirement extends ValidatingRequirement { private String program ; public WhichRequirement ( String program ) { super ( program ) ; this . program = program ; } public Status validate ( ) { try { int result = Runtime . getRuntime ( ) . exec ( new String [ ] { "<STR_LIT>" , program } ) . waitFor ( ) ; if ( result != <NUM_LIT:0> ) { return new Status ( FAIL , Installer . getString ( program + "<STR_LIT>" ) ) ; } } catch ( Exception e ) { logger . error ( "<STR_LIT>" + program + "<STR_LIT:'>" , e ) ; return new Status ( WARN , Installer . getString ( program + "<STR_LIT>" ) ) ; } return OK_STATUS ; } } } </s>
|
<s> package org . eclim . installer . step ; import org . apache . commons . lang . StringUtils ; public class Dependency { private String id ; private String site ; private boolean upgrade ; private Feature feature ; private String requiredVersion ; public Dependency ( String id , String site , String requiredVersion , Feature feature ) { this . id = id ; this . site = site ; this . requiredVersion = requiredVersion ; this . feature = feature ; if ( feature != null ) { this . upgrade = compareVersions ( this . requiredVersion , feature . getVersion ( ) ) < <NUM_LIT:0> ; } } public String getId ( ) { return id ; } public String getRequiredVersion ( ) { return requiredVersion ; } public boolean isInstalled ( ) { return feature != null ; } public boolean isUpgrade ( ) { return upgrade ; } public Feature getFeature ( ) { return feature ; } public String getSite ( ) { return this . site ; } private int compareVersions ( String v1 , String v2 ) { String [ ] dv = StringUtils . split ( v1 , "<STR_LIT:.>" ) ; String [ ] fv = StringUtils . split ( v2 , "<STR_LIT:.>" ) ; for ( int ii = <NUM_LIT:0> ; ii < dv . length ; ii ++ ) { int dp = Integer . parseInt ( dv [ ii ] ) ; int fp = Integer . parseInt ( fv [ ii ] ) ; if ( dp != fp ) { return fp - dp ; } } return <NUM_LIT:0> ; } } </s>
|
<s> package org . eclim . installer . step ; import java . io . File ; import java . net . URL ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import javax . xml . parsers . DocumentBuilderFactory ; import org . apache . commons . lang . StringUtils ; import org . apache . tools . ant . taskdefs . condition . Os ; import org . eclim . installer . step . command . Command ; import org . eclim . installer . step . command . InfoCommand ; import org . eclim . installer . step . command . InstallCommand ; import org . eclim . installer . step . command . OutputHandler ; import org . eclim . installer . step . command . UninstallCommand ; import org . formic . Installer ; import org . formic . util . Extractor ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class EclipseInfo { private static final Logger logger = LoggerFactory . getLogger ( EclipseInfo . class ) ; private static final String DEPENDENCIES = "<STR_LIT>" ; private static final String PROFILE = "<STR_LIT>" ; private static final String CONFIGURATION = "<STR_LIT>" ; private static final String FEATURE = "<STR_LIT>" ; private Map < String , Feature > installedFeatures ; private Map < String , List < Dependency > > dependencies = new HashMap < String , List < Dependency > > ( ) ; private String profileName ; private String localPath ; public EclipseInfo ( String profileName , String localPath , Map < String , Feature > installedFeatures ) throws Exception { this . profileName = profileName ; this . localPath = localPath ; this . installedFeatures = installedFeatures ; Document document = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . parse ( EclipseInfo . class . getResource ( DEPENDENCIES ) . toString ( ) ) ; Element root = document . getDocumentElement ( ) ; NodeList features = root . getElementsByTagName ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < features . getLength ( ) ; i ++ ) { Element feature = ( Element ) features . item ( i ) ; List < Dependency > dependencies = new ArrayList < Dependency > ( ) ; NodeList deps = feature . getElementsByTagName ( "<STR_LIT>" ) ; for ( int j = <NUM_LIT:0> ; j < deps . getLength ( ) ; j ++ ) { Element node = ( Element ) deps . item ( j ) ; Element site = ( Element ) node . getElementsByTagName ( "<STR_LIT>" ) . item ( <NUM_LIT:0> ) ; dependencies . add ( new Dependency ( node . getAttribute ( "<STR_LIT:id>" ) , site . getAttribute ( "<STR_LIT:url>" ) , node . getAttribute ( "<STR_LIT:version>" ) , this . installedFeatures . get ( node . getAttribute ( "<STR_LIT:id>" ) ) ) ) ; } this . dependencies . put ( feature . getAttribute ( "<STR_LIT:id>" ) , dependencies ) ; } } public String getProfileName ( ) { return profileName ; } public String getLocalPath ( ) { return localPath ; } public boolean hasFeature ( String name ) { return this . installedFeatures . containsKey ( name ) ; } public List < Dependency > getDependencies ( String plugin ) { List < Dependency > deps = dependencies . get ( plugin ) ; if ( deps == null ) { return new ArrayList < Dependency > ( ) ; } return deps ; } public List < Dependency > getUninstalledDependencies ( String plugin ) { List < Dependency > deps = new ArrayList < Dependency > ( ) ; for ( Dependency dep : getDependencies ( plugin ) ) { if ( ! dep . isInstalled ( ) ) { deps . add ( dep ) ; } } return deps ; } public List < Dependency > getUnsatisfiedDependencies ( String plugin ) { List < Dependency > deps = new ArrayList < Dependency > ( ) ; for ( Dependency dep : getDependencies ( plugin ) ) { if ( ! dep . isInstalled ( ) || dep . isUpgrade ( ) ) { deps . add ( dep ) ; } } return deps ; } public static boolean installInstallerPlugin ( ) throws Exception { File updateDir = Installer . tempDir ( "<STR_LIT>" ) ; Extractor . extractResource ( "<STR_LIT>" , updateDir ) ; String url = "<STR_LIT>" + updateDir ; Command command = new InstallCommand ( null , url , "<STR_LIT>" , "<STR_LIT>" ) ; try { command . start ( ) ; command . join ( ) ; if ( command . getReturnCode ( ) != <NUM_LIT:0> ) { if ( command . isShutdown ( ) ) { return false ; } RuntimeException re = new RuntimeException ( "<STR_LIT>" + command . getErrorMessage ( ) + "<STR_LIT>" + command . getResult ( ) ) ; logger . warn ( "<STR_LIT>" + "<STR_LIT>" ) ; Command uninstall = new UninstallCommand ( null , url , "<STR_LIT>" , "<STR_LIT>" ) ; uninstall . start ( ) ; uninstall . join ( ) ; command = new InstallCommand ( null , url , "<STR_LIT>" , "<STR_LIT>" ) ; command . start ( ) ; command . join ( ) ; if ( command . getReturnCode ( ) != <NUM_LIT:0> ) { if ( command . isShutdown ( ) ) { return false ; } throw re ; } } Installer . getProject ( ) . setProperty ( "<STR_LIT>" , "<STR_LIT:true>" ) ; Installer . getProject ( ) . setProperty ( "<STR_LIT>" , url ) ; } finally { command . destroy ( ) ; } return true ; } public static EclipseInfo gatherEclipseInfo ( ) throws Exception { final Map < String , Feature > installedFeatures = new HashMap < String , Feature > ( ) ; Command command = new InfoCommand ( new OutputHandler ( ) { public void process ( String line ) { logger . info ( line ) ; if ( line . startsWith ( FEATURE ) ) { String [ ] attrs = StringUtils . split ( line . substring ( FEATURE . length ( ) ) ) ; File site = null ; try { site = new File ( new URL ( attrs [ <NUM_LIT:2> ] ) . getFile ( ) ) ; } catch ( Exception e ) { logger . error ( "<STR_LIT>" + line , e ) ; } installedFeatures . put ( attrs [ <NUM_LIT:0> ] , new Feature ( attrs [ <NUM_LIT:1> ] , site ) ) ; } else if ( line . startsWith ( CONFIGURATION ) ) { String config = line . substring ( CONFIGURATION . length ( ) ) ; if ( config . startsWith ( "<STR_LIT>" ) ) { config = config . substring ( <NUM_LIT:5> ) ; } if ( Os . isFamily ( Os . FAMILY_WINDOWS ) && config . startsWith ( "<STR_LIT:/>" ) ) { config = config . substring ( <NUM_LIT:1> ) ; } String local = new File ( config ) . getParent ( ) ; logger . info ( "<STR_LIT>" + local ) ; Installer . getContext ( ) . setValue ( "<STR_LIT>" , local ) ; } else if ( line . startsWith ( PROFILE ) ) { String profile = line . substring ( PROFILE . length ( ) ) ; logger . info ( "<STR_LIT>" + profile ) ; Installer . getContext ( ) . setValue ( "<STR_LIT>" , profile ) ; } } } ) ; try { command . start ( ) ; command . join ( ) ; if ( command . getReturnCode ( ) != <NUM_LIT:0> ) { if ( command . isShutdown ( ) ) { return null ; } throw new RuntimeException ( "<STR_LIT>" + command . getErrorMessage ( ) + "<STR_LIT>" + command . getResult ( ) ) ; } } finally { command . destroy ( ) ; } return new EclipseInfo ( ( String ) Installer . getContext ( ) . getValue ( "<STR_LIT>" ) , ( String ) Installer . getContext ( ) . getValue ( "<STR_LIT>" ) , installedFeatures ) ; } } </s>
|
<s> package org . eclim . installer . step ; import java . awt . Component ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . io . FileInputStream ; import java . util . ArrayList ; import java . util . Properties ; import javax . swing . JCheckBox ; import javax . swing . JFileChooser ; import javax . swing . JLabel ; import javax . swing . JList ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JTextField ; import javax . swing . ListSelectionModel ; import javax . swing . event . ListSelectionEvent ; import javax . swing . event . ListSelectionListener ; import javax . swing . filechooser . FileFilter ; import org . apache . commons . io . IOUtils ; import org . apache . commons . lang . StringUtils ; import org . apache . tools . ant . BuildException ; import org . apache . tools . ant . taskdefs . Delete ; import org . apache . tools . ant . taskdefs . condition . Os ; import org . apache . tools . ant . types . FileSet ; import org . formic . InstallContext ; import org . formic . Installer ; import org . formic . util . CommandExecutor ; import org . formic . util . File ; import org . formic . util . dialog . gui . GuiDialogs ; import org . formic . wizard . form . GuiForm ; import org . formic . wizard . form . Validator ; import org . formic . wizard . form . gui . component . FileChooser ; import org . formic . wizard . form . validator . ValidatorBuilder ; import org . formic . wizard . step . AbstractGuiStep ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import foxtrot . Task ; import foxtrot . Worker ; import net . miginfocom . swing . MigLayout ; public class VimStep extends AbstractGuiStep { private static final Logger logger = LoggerFactory . getLogger ( VimStep . class ) ; private static final String [ ] WINDOWS_VIMS = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , } ; private static final String [ ] WINDOWS_GVIMS = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , } ; private static final String [ ] UNIX_VIMS = { "<STR_LIT>" , "<STR_LIT>" } ; private static final String COMMAND = "<STR_LIT>" ; private JPanel panel ; private FileChooser fileChooser ; private JList dirList ; private JCheckBox skipCheckBox ; private boolean rtpAttempted ; private boolean homeVimCreatePrompted ; private String [ ] runtimePath ; public VimStep ( String name , Properties properties ) { super ( name , properties ) ; } public Component init ( ) { GuiForm form = createForm ( ) ; String files = fieldName ( "<STR_LIT>" ) ; fileChooser = new FileChooser ( JFileChooser . DIRECTORIES_ONLY ) ; fileChooser . getFileChooser ( ) . setFileHidingEnabled ( false ) ; fileChooser . getFileChooser ( ) . addChoosableFileFilter ( new FileFilter ( ) { public boolean accept ( java . io . File f ) { String path = f . getAbsolutePath ( ) ; return f . isDirectory ( ) && ( path . matches ( "<STR_LIT>" ) || ! path . matches ( "<STR_LIT>" ) ) ; } public String getDescription ( ) { return null ; } } ) ; String skip = fieldName ( "<STR_LIT>" ) ; skipCheckBox = new JCheckBox ( Installer . getString ( skip ) ) ; skipCheckBox . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { boolean selected = ( ( JCheckBox ) e . getSource ( ) ) . isSelected ( ) ; JTextField fileField = fileChooser . getTextField ( ) ; fileField . setEnabled ( ! selected ) ; fileChooser . getButton ( ) . setEnabled ( ! selected ) ; if ( dirList != null ) { dirList . setEnabled ( ! selected ) ; } Validator validator = ( Validator ) fileField . getClientProperty ( "<STR_LIT>" ) ; setValid ( selected || validator . isValid ( fileField . getText ( ) ) ) ; } } ) ; panel = new JPanel ( new MigLayout ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) ; panel . add ( form . createMessagePanel ( ) , "<STR_LIT>" ) ; panel . add ( new JLabel ( Installer . getString ( files ) ) , "<STR_LIT>" ) ; panel . add ( fileChooser , "<STR_LIT>" ) ; panel . add ( skipCheckBox , "<STR_LIT>" ) ; form . bind ( files , fileChooser . getTextField ( ) , new ValidatorBuilder ( ) . required ( ) . isDirectory ( ) . fileExists ( ) . isWritable ( ) . validator ( ) ) ; return panel ; } public void displayed ( ) { if ( ! rtpAttempted ) { rtpAttempted = true ; setBusy ( true ) ; try { runtimePath = ( String [ ] ) Worker . post ( new Task ( ) { public Object run ( ) throws Exception { setGvimProperty ( ) ; return getVimRuntimePath ( ) ; } } ) ; ArrayList < String > filtered = new ArrayList < String > ( ) ; if ( runtimePath != null ) { for ( String path : runtimePath ) { if ( new File ( path ) . canWrite ( ) ) { if ( Installer . isUninstall ( ) ) { File eclimDir = new File ( path + "<STR_LIT>" ) ; if ( eclimDir . exists ( ) ) { if ( eclimDir . canWrite ( ) ) { filtered . add ( path ) ; } else { logger . warn ( path + "<STR_LIT>" ) ; } } } else { filtered . add ( path ) ; } } } } String [ ] rtp = filtered . toArray ( new String [ filtered . size ( ) ] ) ; if ( rtp == null || rtp . length == <NUM_LIT:0> ) { if ( ! Installer . isUninstall ( ) ) { if ( ! homeVimCreatePrompted ) { createUserVimFiles ( "<STR_LIT>" ) ; } else { GuiDialogs . showWarning ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) ; } } } else { if ( rtp . length == <NUM_LIT:1> ) { fileChooser . getTextField ( ) . setText ( rtp [ <NUM_LIT:0> ] ) ; if ( new File ( rtp [ <NUM_LIT:0> ] + "<STR_LIT>" ) . exists ( ) ) { createUserVimFiles ( "<STR_LIT>" ) ; } } else { dirList = new JList ( rtp ) ; dirList . setSelectionMode ( ListSelectionModel . SINGLE_SELECTION ) ; JScrollPane scrollPane = new JScrollPane ( dirList ) ; panel . add ( scrollPane , "<STR_LIT>" ) ; dirList . addListSelectionListener ( new ListSelectionListener ( ) { public void valueChanged ( ListSelectionEvent event ) { if ( ! event . getValueIsAdjusting ( ) ) { fileChooser . getTextField ( ) . setText ( ( String ) dirList . getSelectedValue ( ) ) ; } } } ) ; dirList . setSelectedIndex ( <NUM_LIT:0> ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } setBusy ( false ) ; fileChooser . getTextField ( ) . grabFocus ( ) ; } } public boolean proceed ( ) { boolean proceed = super . proceed ( ) ; if ( proceed ) { InstallContext context = Installer . getContext ( ) ; context . setValue ( "<STR_LIT>" , Boolean . valueOf ( skipCheckBox . isSelected ( ) ) ) ; String vimfiles = ( String ) context . getValue ( "<STR_LIT>" ) ; if ( vimfiles != null ) { vimfiles = vimfiles . replace ( '<STR_LIT:\\>' , '<CHAR_LIT:/>' ) ; context . setValue ( "<STR_LIT>" , vimfiles ) ; if ( Os . isFamily ( Os . FAMILY_WINDOWS ) ) { vimfiles = vimfiles . toLowerCase ( ) ; } if ( runtimePath != null && runtimePath . length > <NUM_LIT:0> ) { for ( String rpath : runtimePath ) { String path = rpath ; if ( Os . isFamily ( Os . FAMILY_WINDOWS ) ) { path = path . toLowerCase ( ) ; } if ( vimfiles . equals ( path ) ) { continue ; } File fpath = new File ( path + "<STR_LIT>" ) ; if ( ! fpath . exists ( ) ) { continue ; } if ( fpath . canWrite ( ) ) { boolean remove = GuiDialogs . showConfirm ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT:U+0020U+0020>" + rpath + "<STR_LIT:n>" + "<STR_LIT>" ) ; if ( remove ) { Delete delete = new Delete ( ) ; delete . setProject ( Installer . getProject ( ) ) ; delete . setTaskName ( "<STR_LIT>" ) ; delete . setIncludeEmptyDirs ( true ) ; delete . setFailOnError ( true ) ; FileSet set = new FileSet ( ) ; set . setDir ( new File ( path + "<STR_LIT>" ) ) ; set . createInclude ( ) . setName ( "<STR_LIT>" ) ; set . createExclude ( ) . setName ( "<STR_LIT>" ) ; set . createExclude ( ) . setName ( "<STR_LIT>" ) ; delete . addFileset ( set ) ; try { boolean deleted = fpath . delete ( ) ; if ( ! deleted ) { throw new BuildException ( "<STR_LIT>" ) ; } delete . execute ( ) ; } catch ( BuildException be ) { GuiDialogs . showError ( "<STR_LIT>" + "<STR_LIT:U+0020U+0020>" + be . getMessage ( ) + "<STR_LIT:n>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) ; } } proceed = remove ; } else { GuiDialogs . showWarning ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT:U+0020U+0020>" + rpath + "<STR_LIT:n>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) ; } } } } } return proceed ; } private void setGvimProperty ( ) { try { String [ ] gvims = null ; if ( Os . isFamily ( Os . FAMILY_WINDOWS ) ) { gvims = WINDOWS_GVIMS ; for ( String gvim : gvims ) { if ( new File ( gvim ) . isFile ( ) ) { Installer . getProject ( ) . setProperty ( "<STR_LIT>" , gvim ) ; break ; } } } else { String vim = Os . isFamily ( Os . FAMILY_MAC ) ? "<STR_LIT>" : "<STR_LIT>" ; CommandExecutor executor = CommandExecutor . execute ( new String [ ] { "<STR_LIT>" , vim } , <NUM_LIT:1000> ) ; if ( executor . getReturnCode ( ) == <NUM_LIT:0> ) { String result = executor . getResult ( ) . trim ( ) ; logger . info ( "<STR_LIT>" + vim + "<STR_LIT::U+0020>" + result ) ; Installer . getProject ( ) . setProperty ( "<STR_LIT>" , result ) ; } else { logger . info ( "<STR_LIT>" + vim + '<CHAR_LIT::>' + "<STR_LIT>" + executor . getResult ( ) + "<STR_LIT>" + executor . getErrorMessage ( ) ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } } private void createUserVimFiles ( String message ) { homeVimCreatePrompted = true ; File vimfiles = new File ( System . getProperty ( "<STR_LIT>" ) + '<CHAR_LIT:/>' + ( Os . isFamily ( Os . FAMILY_WINDOWS ) ? "<STR_LIT>" : "<STR_LIT>" ) ) ; System . out . println ( "<STR_LIT>" + vimfiles ) ; if ( ! vimfiles . exists ( ) ) { boolean create = GuiDialogs . showConfirm ( message + "<STR_LIT:n>" + "<STR_LIT>" + "<STR_LIT>" + vimfiles ) ; if ( create ) { boolean created = vimfiles . mkdir ( ) ; if ( created ) { rtpAttempted = false ; displayed ( ) ; } else { GuiDialogs . showError ( "<STR_LIT>" + vimfiles ) ; } } } else { fileChooser . getTextField ( ) . setText ( vimfiles . getAbsolutePath ( ) . replace ( '<STR_LIT:\\>' , '<CHAR_LIT:/>' ) ) ; } } private String [ ] getVimRuntimePath ( ) { try { java . io . File tempFile = File . createTempFile ( "<STR_LIT>" , null ) ; String command = COMMAND . replaceFirst ( "<STR_LIT>" , tempFile . getAbsolutePath ( ) . replace ( '<STR_LIT:\\>' , '<CHAR_LIT:/>' ) . replaceAll ( "<STR_LIT:U+0020>" , "<STR_LIT>" ) ) ; String [ ] vims = null ; if ( Os . isFamily ( Os . FAMILY_WINDOWS ) ) { vims = WINDOWS_VIMS ; } else { vims = UNIX_VIMS ; } String [ ] args = { null , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , command , } ; for ( int ii = <NUM_LIT:0> ; ii < vims . length ; ii ++ ) { args [ <NUM_LIT:0> ] = vims [ ii ] ; CommandExecutor executor = CommandExecutor . execute ( args , <NUM_LIT> ) ; if ( executor . getReturnCode ( ) == <NUM_LIT:0> ) { return parseVimRuntimePathResults ( tempFile ) ; } if ( executor . isShutdown ( ) ) { return null ; } executor . destroy ( ) ; } } catch ( Exception e ) { GuiDialogs . showError ( "<STR_LIT>" , e ) ; } return null ; } private String [ ] parseVimRuntimePathResults ( java . io . File file ) { FileInputStream in = null ; try { String contents = IOUtils . toString ( in = new FileInputStream ( file ) ) ; String [ ] paths = StringUtils . stripAll ( StringUtils . split ( contents , '<CHAR_LIT:U+002C>' ) ) ; ArrayList < String > results = new ArrayList < String > ( ) ; for ( String path : paths ) { if ( new File ( path ) . isDirectory ( ) ) { results . add ( path . replace ( '<STR_LIT:\\>' , '<CHAR_LIT:/>' ) ) ; } } return results . toArray ( new String [ results . size ( ) ] ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { IOUtils . closeQuietly ( in ) ; file . deleteOnExit ( ) ; file . delete ( ) ; } return null ; } } </s>
|
<s> package org . eclim . installer . theme ; import javax . swing . plaf . ColorUIResource ; public class DesertBlue extends com . jgoodies . looks . plastic . theme . DesertBlue { protected ColorUIResource getPrimary1 ( ) { return new ColorUIResource ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ; } } </s>
|
<s> package org . eclim . installer ; import java . io . FilterInputStream ; import java . io . IOException ; import java . net . URLConnection ; import javax . swing . JProgressBar ; public class URLProgressInputStream extends FilterInputStream { private JProgressBar progressBar ; public URLProgressInputStream ( JProgressBar progressBar , URLConnection con ) throws IOException { super ( con . getInputStream ( ) ) ; this . progressBar = progressBar ; progressBar . setValue ( <NUM_LIT:0> ) ; progressBar . setMaximum ( con . getContentLength ( ) ) ; progressBar . setIndeterminate ( false ) ; } @ Override public int read ( ) throws IOException { int value = super . read ( ) ; progressBar . setValue ( progressBar . getValue ( ) + <NUM_LIT:1> ) ; return value ; } @ Override public int read ( byte [ ] b ) throws IOException { return read ( b , <NUM_LIT:0> , b . length ) ; } @ Override public int read ( byte [ ] b , int off , int len ) throws IOException { int result = super . read ( b , off , len ) ; if ( result < <NUM_LIT:0> ) { progressBar . setValue ( progressBar . getMaximum ( ) ) ; } else { progressBar . setValue ( progressBar . getValue ( ) + result ) ; } return result ; } @ Override public long skip ( long n ) throws IOException { long result = super . skip ( n ) ; progressBar . setValue ( progressBar . getValue ( ) + ( int ) result ) ; return result ; } } </s>
|
<s> package org . eclim . installer . eclipse ; import java . io . PrintStream ; import java . lang . reflect . Field ; import java . lang . reflect . Method ; import java . net . URI ; import java . util . Collection ; import java . util . List ; import org . apache . commons . lang . StringUtils ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IBundleGroup ; import org . eclipse . core . runtime . IBundleGroupProvider ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Platform ; import org . eclipse . equinox . app . IApplication ; import org . eclipse . equinox . internal . p2 . director . ProfileChangeRequest ; import org . eclipse . equinox . internal . p2 . director . app . Messages ; import org . eclipse . equinox . internal . provisional . p2 . director . PlanExecutionHelper ; import org . eclipse . equinox . p2 . core . IProvisioningAgent ; import org . eclipse . equinox . p2 . core . ProvisionException ; import org . eclipse . equinox . p2 . engine . IEngine ; import org . eclipse . equinox . p2 . engine . IProfile ; import org . eclipse . equinox . p2 . engine . IProvisioningPlan ; import org . eclipse . equinox . p2 . engine . ProvisioningContext ; import org . eclipse . equinox . p2 . metadata . IInstallableUnit ; import org . eclipse . equinox . p2 . metadata . IVersionedId ; import org . eclipse . equinox . p2 . planner . IPlanner ; import org . eclipse . osgi . util . NLS ; import org . eclipse . update . internal . configurator . FeatureEntry ; import org . osgi . framework . ServiceReference ; @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) public class Application extends org . eclipse . equinox . internal . p2 . director . app . DirectorApplication { private static final Integer EXIT_ERROR = new Integer ( <NUM_LIT> ) ; private Object invokePrivate ( String methodName , Class [ ] params , Object [ ] args ) throws Exception { Method method = org . eclipse . equinox . internal . p2 . director . app . DirectorApplication . class . getDeclaredMethod ( methodName , params ) ; method . setAccessible ( true ) ; return method . invoke ( this , args ) ; } private Object getPrivateField ( String fieldName ) throws Exception { Field field = org . eclipse . equinox . internal . p2 . director . app . DirectorApplication . class . getDeclaredField ( fieldName ) ; field . setAccessible ( true ) ; return field . get ( this ) ; } public Object run ( String [ ] args ) { if ( "<STR_LIT>" . equals ( args [ <NUM_LIT:0> ] ) ) { System . out . println ( "<STR_LIT>" + System . getProperty ( "<STR_LIT>" ) ) ; System . out . println ( "<STR_LIT>" + System . getProperty ( "<STR_LIT>" ) ) ; IBundleGroupProvider [ ] providers = Platform . getBundleGroupProviders ( ) ; for ( IBundleGroupProvider provider : providers ) { IBundleGroup [ ] groups = provider . getBundleGroups ( ) ; for ( IBundleGroup group : groups ) { FeatureEntry feature = ( FeatureEntry ) group ; System . out . println ( "<STR_LIT>" + feature . getIdentifier ( ) + '<CHAR_LIT:U+0020>' + feature . getVersion ( ) + '<CHAR_LIT:U+0020>' + feature . getSite ( ) . getResolvedURL ( ) ) ; } } return IApplication . EXIT_OK ; } long time = System . currentTimeMillis ( ) ; try { processArguments ( args ) ; boolean printHelpInfo = ( ( Boolean ) this . getPrivateField ( "<STR_LIT>" ) ) . booleanValue ( ) ; boolean printIUList = ( ( Boolean ) this . getPrivateField ( "<STR_LIT>" ) ) . booleanValue ( ) ; boolean printRootIUList = ( ( Boolean ) this . getPrivateField ( "<STR_LIT>" ) ) . booleanValue ( ) ; boolean printTags = ( ( Boolean ) this . getPrivateField ( "<STR_LIT>" ) ) . booleanValue ( ) ; boolean purgeRegistry = ( ( Boolean ) this . getPrivateField ( "<STR_LIT>" ) ) . booleanValue ( ) ; if ( printHelpInfo ) { invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; } else { invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; String NOTHING_TO_REVERT_TO = ( String ) this . getPrivateField ( "<STR_LIT>" ) ; String revertToPreviousState = ( String ) this . getPrivateField ( "<STR_LIT>" ) ; List < IVersionedId > rootsToInstall = ( List < IVersionedId > ) this . getPrivateField ( "<STR_LIT>" ) ; List < IVersionedId > rootsToUninstall = ( List < IVersionedId > ) this . getPrivateField ( "<STR_LIT>" ) ; if ( revertToPreviousState != NOTHING_TO_REVERT_TO ) { invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; } else if ( ! ( rootsToInstall . isEmpty ( ) && rootsToUninstall . isEmpty ( ) ) ) performProvisioningActions ( ) ; if ( printIUList ) invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; if ( printRootIUList ) invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; if ( printTags ) invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; if ( purgeRegistry ) invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; System . out . println ( NLS . bind ( Messages . Operation_complete , new Long ( System . currentTimeMillis ( ) - time ) ) ) ; } return IApplication . EXIT_OK ; } catch ( CoreException e ) { try { invokePrivate ( "<STR_LIT>" , new Class [ ] { IStatus . class , PrintStream . class , Integer . TYPE } , new Object [ ] { e . getStatus ( ) , System . err , <NUM_LIT:0> } ) ; invokePrivate ( "<STR_LIT>" , new Class [ ] { IStatus . class } , new Object [ ] { e . getStatus ( ) } ) ; invokePrivate ( "<STR_LIT>" , new Class [ ] { String . class , String . class } , new Object [ ] { "<STR_LIT>" , "<STR_LIT>" } ) ; String workspace = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getRawLocation ( ) . toOSString ( ) ; String log = workspace + "<STR_LIT>" ; throw new RuntimeException ( "<STR_LIT>" + log + "<STR_LIT>" , e ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; return EXIT_ERROR ; } } catch ( Exception e ) { e . printStackTrace ( ) ; return EXIT_ERROR ; } finally { try { ServiceReference packageAdminRef = ( ServiceReference ) this . getPrivateField ( "<STR_LIT>" ) ; if ( packageAdminRef != null ) { invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } private void performProvisioningActions ( ) throws Exception { List < IVersionedId > rootsToInstall = ( List < IVersionedId > ) this . getPrivateField ( "<STR_LIT>" ) ; List < IVersionedId > rootsToUninstall = ( List < IVersionedId > ) this . getPrivateField ( "<STR_LIT>" ) ; IProfile profile = ( IProfile ) invokePrivate ( "<STR_LIT>" , new Class [ <NUM_LIT:0> ] , new Object [ <NUM_LIT:0> ] ) ; Collection < IInstallableUnit > installs = ( Collection < IInstallableUnit > ) invokePrivate ( "<STR_LIT>" , new Class [ ] { IProfile . class , List . class , Boolean . TYPE } , new Object [ ] { profile , rootsToInstall , true } ) ; Collection < IInstallableUnit > uninstalls = ( Collection < IInstallableUnit > ) invokePrivate ( "<STR_LIT>" , new Class [ ] { IProfile . class , List . class , Boolean . TYPE } , new Object [ ] { profile , rootsToUninstall , false } ) ; boolean wasRoaming = Boolean . valueOf ( profile . getProperty ( IProfile . PROP_ROAMING ) ) . booleanValue ( ) ; try { invokePrivate ( "<STR_LIT>" , new Class [ ] { IProfile . class } , new Object [ ] { profile } ) ; IProvisioningAgent targetAgent = ( IProvisioningAgent ) this . getPrivateField ( "<STR_LIT>" ) ; List < URI > metadataRepositoryLocations = ( List < URI > ) this . getPrivateField ( "<STR_LIT>" ) ; List < URI > artifactRepositoryLocations = ( List < URI > ) this . getPrivateField ( "<STR_LIT>" ) ; boolean followReferences = ( ( Boolean ) this . getPrivateField ( "<STR_LIT>" ) ) . booleanValue ( ) ; String FOLLOW_ARTIFACT_REPOSITORY_REFERENCES = ( String ) this . getPrivateField ( "<STR_LIT>" ) ; ProvisioningContext context = new ProvisioningContext ( targetAgent ) ; context . setMetadataRepositories ( metadataRepositoryLocations . toArray ( new URI [ metadataRepositoryLocations . size ( ) ] ) ) ; context . setArtifactRepositories ( artifactRepositoryLocations . toArray ( new URI [ artifactRepositoryLocations . size ( ) ] ) ) ; context . setProperty ( ProvisioningContext . FOLLOW_REPOSITORY_REFERENCES , String . valueOf ( followReferences ) ) ; context . setProperty ( FOLLOW_ARTIFACT_REPOSITORY_REFERENCES , String . valueOf ( followReferences ) ) ; ProfileChangeRequest request = ( ProfileChangeRequest ) invokePrivate ( "<STR_LIT>" , new Class [ ] { IProfile . class , Collection . class , Collection . class } , new Object [ ] { profile , installs , uninstalls } ) ; invokePrivate ( "<STR_LIT>" , new Class [ ] { ProfileChangeRequest . class } , new Object [ ] { request } ) ; planAndExecute ( profile , context , request ) ; } finally { if ( wasRoaming && ! Boolean . valueOf ( profile . getProperty ( IProfile . PROP_ROAMING ) ) . booleanValue ( ) ) invokePrivate ( "<STR_LIT>" , new Class [ ] { IProfile . class } , new Object [ ] { profile } ) ; } } private void planAndExecute ( IProfile profile , ProvisioningContext context , ProfileChangeRequest request ) throws Exception { IPlanner planner = ( IPlanner ) this . getPrivateField ( "<STR_LIT>" ) ; IProvisioningPlan result = planner . getProvisioningPlan ( request , context , new NullProgressMonitor ( ) ) ; IStatus operationStatus = result . getStatus ( ) ; if ( ! operationStatus . isOK ( ) ) throw new CoreException ( operationStatus ) ; executePlan ( context , result ) ; } private void executePlan ( ProvisioningContext context , IProvisioningPlan result ) throws Exception { IEngine engine = ( IEngine ) this . getPrivateField ( "<STR_LIT>" ) ; boolean verifyOnly = ( ( Boolean ) this . getPrivateField ( "<STR_LIT>" ) ) . booleanValue ( ) ; boolean noArtifactRepositorySpecified = ( ( Boolean ) this . getPrivateField ( "<STR_LIT>" ) ) . booleanValue ( ) ; IStatus operationStatus ; if ( ! verifyOnly ) { operationStatus = PlanExecutionHelper . executePlan ( result , engine , context , new ProgressMonitor ( ) ) ; if ( ! operationStatus . isOK ( ) ) { boolean hasNoRepositoryFound = ( ( Boolean ) invokePrivate ( "<STR_LIT>" , new Class [ ] { IStatus . class } , new Object [ ] { operationStatus } ) ) . booleanValue ( ) ; if ( noArtifactRepositorySpecified && hasNoRepositoryFound ) throw new ProvisionException ( Messages . Application_NoRepositories ) ; throw new CoreException ( operationStatus ) ; } } } private static class ProgressMonitor implements IProgressMonitor { private double totalWorked ; private boolean canceled ; public void beginTask ( String name , int totalWork ) { System . out . println ( "<STR_LIT>" + totalWork + "<STR_LIT>" + name ) ; } public void done ( ) { System . out . println ( "<STR_LIT>" ) ; } public void internalWorked ( double work ) { totalWorked += work ; System . out . println ( "<STR_LIT>" + totalWorked ) ; } public boolean isCanceled ( ) { return canceled ; } public void setCanceled ( boolean canceled ) { this . canceled = canceled ; } public void setTaskName ( String name ) { System . out . println ( "<STR_LIT>" + name ) ; } public void subTask ( String name ) { if ( name != null && ! name . trim ( ) . equals ( StringUtils . EMPTY ) ) { System . out . println ( "<STR_LIT>" + name ) ; } } public void worked ( int work ) { totalWorked += work ; System . out . println ( "<STR_LIT>" + totalWorked ) ; } } } </s>
|
<s> package org . eclim . installer . eclipse ; import org . osgi . framework . BundleContext ; public class Plugin extends org . eclipse . core . runtime . Plugin { private static Plugin plugin ; public Plugin ( ) { plugin = this ; } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; } public void stop ( BundleContext context ) throws Exception { super . stop ( context ) ; plugin = null ; } public static Plugin getDefault ( ) { return plugin ; } } </s>
|
<s> package org . eclim . plugin . $ { plugin } ; import org . eclim . Services ; import org . eclim . plugin . AbstractPluginResources ; public class PluginResources extends AbstractPluginResources { public static final String NAME = "<STR_LIT>" ; @ Override public void initialize ( String name ) { super . initialize ( name ) ; } protected String getBundleBaseName ( ) { return "<STR_LIT>" ; } } </s>
|
<s> package org . eclim . testng ; import org . testng . ITestResult ; import org . testng . TestListenerAdapter ; public class TestNgListener extends TestListenerAdapter { public void onTestFailure ( ITestResult result ) { System . out . println ( "<STR_LIT>" + result . getTestClass ( ) . getName ( ) + '<CHAR_LIT::>' + result . getMethod ( ) . getMethodName ( ) ) ; } } </s>
|
<s> package org . eclim . checkstyle ; import com . puppycrawl . tools . checkstyle . api . TokenTypes ; import com . puppycrawl . tools . checkstyle . api . DetailAST ; import com . puppycrawl . tools . checkstyle . api . Utils ; import com . puppycrawl . tools . checkstyle . checks . blocks . LeftCurlyCheck ; import com . puppycrawl . tools . checkstyle . checks . blocks . LeftCurlyOption ; public class LeftCurly extends LeftCurlyCheck { private static final int DEFAULT_MAX_LINE_LENGTH = <NUM_LIT> ; private int mMaxLineLength = DEFAULT_MAX_LINE_LENGTH ; private boolean ignoreAnonymous ; public void setIgnoreAnonymousClassMethods ( boolean ignoreAnonymous ) { this . ignoreAnonymous = ignoreAnonymous ; } @ Override public void visitToken ( DetailAST aAST ) { final DetailAST startToken ; final DetailAST brace ; switch ( aAST . getType ( ) ) { case TokenTypes . CTOR_DEF : case TokenTypes . METHOD_DEF : startToken = skipAnnotationOnlyLines ( aAST ) ; brace = aAST . findFirstToken ( TokenTypes . SLIST ) ; break ; case TokenTypes . INTERFACE_DEF : case TokenTypes . CLASS_DEF : case TokenTypes . ANNOTATION_DEF : case TokenTypes . ENUM_DEF : case TokenTypes . ENUM_CONSTANT_DEF : startToken = skipAnnotationOnlyLines ( aAST ) ; final DetailAST objBlock = aAST . findFirstToken ( TokenTypes . OBJBLOCK ) ; brace = ( objBlock == null ) ? null : ( DetailAST ) objBlock . getFirstChild ( ) ; break ; case TokenTypes . LITERAL_WHILE : case TokenTypes . LITERAL_CATCH : case TokenTypes . LITERAL_SYNCHRONIZED : case TokenTypes . LITERAL_FOR : case TokenTypes . LITERAL_TRY : case TokenTypes . LITERAL_FINALLY : case TokenTypes . LITERAL_DO : case TokenTypes . LITERAL_IF : startToken = aAST ; brace = aAST . findFirstToken ( TokenTypes . SLIST ) ; break ; case TokenTypes . LITERAL_ELSE : startToken = aAST ; final DetailAST candidate = aAST . getFirstChild ( ) ; brace = ( candidate . getType ( ) == TokenTypes . SLIST ) ? candidate : null ; break ; case TokenTypes . LITERAL_SWITCH : startToken = aAST ; brace = aAST . findFirstToken ( TokenTypes . LCURLY ) ; break ; default : startToken = null ; brace = null ; } if ( ( brace != null ) && ( startToken != null ) ) { verifyBrace ( brace , startToken ) ; } } private DetailAST skipAnnotationOnlyLines ( DetailAST aAST ) { final DetailAST modifiers = aAST . findFirstToken ( TokenTypes . MODIFIERS ) ; if ( modifiers == null ) { return aAST ; } DetailAST lastAnnot = findLastAnnotation ( modifiers ) ; if ( lastAnnot == null ) { return aAST ; } final DetailAST tokenAfterLast = lastAnnot . getNextSibling ( ) != null ? lastAnnot . getNextSibling ( ) : modifiers . getNextSibling ( ) ; if ( tokenAfterLast . getLineNo ( ) > lastAnnot . getLineNo ( ) ) { return tokenAfterLast ; } final int lastAnnotLineNumber = lastAnnot . getLineNo ( ) ; while ( lastAnnot . getPreviousSibling ( ) != null && ( lastAnnot . getPreviousSibling ( ) . getLineNo ( ) == lastAnnotLineNumber ) ) { lastAnnot = lastAnnot . getPreviousSibling ( ) ; } return lastAnnot ; } private DetailAST findLastAnnotation ( DetailAST aModifiers ) { DetailAST aAnnot = aModifiers . findFirstToken ( TokenTypes . ANNOTATION ) ; while ( aAnnot != null && aAnnot . getNextSibling ( ) != null && aAnnot . getNextSibling ( ) . getType ( ) == TokenTypes . ANNOTATION ) { aAnnot = aAnnot . getNextSibling ( ) ; } return aAnnot ; } private void verifyBrace ( final DetailAST aBrace , final DetailAST aStartToken ) { final String braceLine = getLines ( ) [ aBrace . getLineNo ( ) - <NUM_LIT:1> ] ; final int prevLineLen = ( aBrace . getLineNo ( ) == <NUM_LIT:1> ) ? mMaxLineLength : Utils . lengthMinusTrailingWhitespace ( getLines ( ) [ aBrace . getLineNo ( ) - <NUM_LIT:2> ] ) ; if ( ( braceLine . length ( ) > ( aBrace . getColumnNo ( ) + <NUM_LIT:1> ) ) && ( braceLine . charAt ( aBrace . getColumnNo ( ) + <NUM_LIT:1> ) == '<CHAR_LIT:}>' ) ) { ; } else if ( getAbstractOption ( ) == LeftCurlyOption . NL ) { if ( ! Utils . whitespaceBefore ( aBrace . getColumnNo ( ) , braceLine ) ) { if ( ignoreAnonymous && aStartToken . getType ( ) == TokenTypes . METHOD_DEF ) { DetailAST parent = aStartToken . getParent ( ) ; if ( parent != null ) { parent = parent . getParent ( ) ; } if ( parent != null && parent . getType ( ) == TokenTypes . LITERAL_NEW ) { return ; } } log ( aBrace . getLineNo ( ) , aBrace . getColumnNo ( ) , "<STR_LIT>" , "<STR_LIT:{>" ) ; } } else if ( getAbstractOption ( ) == LeftCurlyOption . EOL ) { if ( Utils . whitespaceBefore ( aBrace . getColumnNo ( ) , braceLine ) && ( ( prevLineLen + <NUM_LIT:2> ) <= mMaxLineLength ) ) { log ( aBrace . getLineNo ( ) , aBrace . getColumnNo ( ) , "<STR_LIT>" , "<STR_LIT:{>" ) ; } } else if ( getAbstractOption ( ) == LeftCurlyOption . NLOW ) { if ( aStartToken . getLineNo ( ) == aBrace . getLineNo ( ) ) { ; } else if ( ( aStartToken . getLineNo ( ) + <NUM_LIT:1> ) == aBrace . getLineNo ( ) ) { if ( ! Utils . whitespaceBefore ( aBrace . getColumnNo ( ) , braceLine ) ) { log ( aBrace . getLineNo ( ) , aBrace . getColumnNo ( ) , "<STR_LIT>" , "<STR_LIT:{>" ) ; } else if ( ( prevLineLen + <NUM_LIT:2> ) <= mMaxLineLength ) { log ( aBrace . getLineNo ( ) , aBrace . getColumnNo ( ) , "<STR_LIT>" , "<STR_LIT:{>" ) ; } } else if ( ! Utils . whitespaceBefore ( aBrace . getColumnNo ( ) , braceLine ) ) { log ( aBrace . getLineNo ( ) , aBrace . getColumnNo ( ) , "<STR_LIT>" , "<STR_LIT:{>" ) ; } } } @ Override protected String getMessageBundle ( ) { String className = getClass ( ) . getSuperclass ( ) . getName ( ) ; String packageName = className . substring ( <NUM_LIT:0> , className . lastIndexOf ( '<CHAR_LIT:.>' ) ) ; return packageName + "<STR_LIT>" ; } } </s>
|
<s> package org . eclim . checkstyle ; import com . puppycrawl . tools . checkstyle . api . TokenTypes ; import com . puppycrawl . tools . checkstyle . api . DetailAST ; public class WhitespaceAfterCheck extends com . puppycrawl . tools . checkstyle . checks . whitespace . WhitespaceAfterCheck { @ Override public void visitToken ( DetailAST aAST ) { final Object [ ] message ; final DetailAST targetAST ; if ( aAST . getType ( ) == TokenTypes . TYPECAST ) { targetAST = aAST . findFirstToken ( TokenTypes . RPAREN ) ; message = new Object [ ] { "<STR_LIT:cast>" } ; } else { targetAST = aAST ; message = new Object [ ] { aAST . getText ( ) } ; } final String line = getLines ( ) [ targetAST . getLineNo ( ) - <NUM_LIT:1> ] ; final int after = targetAST . getColumnNo ( ) + targetAST . getText ( ) . length ( ) ; if ( after < line . length ( ) ) { final char charAfter = line . charAt ( after ) ; if ( ( targetAST . getType ( ) == TokenTypes . SEMI ) && ( ( charAfter == '<CHAR_LIT:;>' ) || ( charAfter == '<CHAR_LIT:)>' ) ) ) { return ; } if ( ! Character . isWhitespace ( charAfter ) ) { if ( targetAST . getType ( ) == TokenTypes . SEMI ) { final DetailAST sibling = targetAST . getNextSibling ( ) ; if ( ( sibling != null ) && ( sibling . getType ( ) == TokenTypes . FOR_ITERATOR ) && ( sibling . getChildCount ( ) == <NUM_LIT:0> ) ) { return ; } } if ( targetAST . getType ( ) == TokenTypes . COMMA ) { final DetailAST sibling = targetAST . getNextSibling ( ) ; if ( sibling != null && sibling . getType ( ) == TokenTypes . TYPE_ARGUMENT ) { return ; } } log ( targetAST . getLineNo ( ) , targetAST . getColumnNo ( ) + targetAST . getText ( ) . length ( ) , "<STR_LIT>" , message ) ; } } } @ Override protected String getMessageBundle ( ) { String className = getClass ( ) . getSuperclass ( ) . getName ( ) ; String packageName = className . substring ( <NUM_LIT:0> , className . lastIndexOf ( '<CHAR_LIT:.>' ) ) ; return packageName + "<STR_LIT>" ; } } </s>
|
<s> package org . eclim . plugin . dltk . util ; import java . io . InputStream ; import java . util . ArrayList ; import org . eclim . Services ; import org . eclim . util . IOUtils ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . Path ; import org . eclipse . dltk . compiler . env . IModuleSource ; import org . eclipse . dltk . compiler . env . ModuleSource ; import org . eclipse . dltk . core . DLTKCore ; import org . eclipse . dltk . core . IProjectFragment ; import org . eclipse . dltk . core . IScriptFolder ; import org . eclipse . dltk . core . IScriptProject ; import org . eclipse . dltk . core . ISourceModule ; import org . eclipse . dltk . internal . core . util . Util ; public class DltkUtils { private static ArrayList < String > natures = new ArrayList < String > ( ) ; public static void addDltkNature ( String nature ) { if ( ! natures . contains ( nature ) ) { natures . add ( nature ) ; } } public static String [ ] getDltkNatures ( ) { return natures . toArray ( new String [ natures . size ( ) ] ) ; } public static IModuleSource getModuleSource ( IFile file ) throws Exception { InputStream in = file . getContents ( ) ; try { String path = file . getLocation ( ) . toOSString ( ) ; return new ModuleSource ( path , IOUtils . toString ( in ) ) ; } finally { IOUtils . closeQuietly ( in ) ; } } public static ISourceModule getSourceModule ( IFile file ) throws Exception { IPath path = file . getFullPath ( ) ; IProject project = file . getProject ( ) ; IScriptProject scriptProject = DLTKCore . create ( project ) ; IProjectFragment [ ] roots = scriptProject . getProjectFragments ( ) ; ISourceModule module = null ; for ( int j = <NUM_LIT:0> , rootCount = roots . length ; j < rootCount ; j ++ ) { final IProjectFragment root = roots [ j ] ; IPath rootPath = root . getPath ( ) ; if ( rootPath . isPrefixOf ( path ) && ! Util . isExcluded ( path , root , false ) ) { IPath localPath = path . setDevice ( null ) . removeFirstSegments ( rootPath . segmentCount ( ) ) ; if ( localPath . segmentCount ( ) >= <NUM_LIT:1> ) { final IScriptFolder folder ; if ( localPath . segmentCount ( ) > <NUM_LIT:1> ) { folder = root . getScriptFolder ( localPath . removeLastSegments ( <NUM_LIT:1> ) ) ; } else { folder = root . getScriptFolder ( Path . EMPTY ) ; } module = folder . getSourceModule ( localPath . lastSegment ( ) ) ; break ; } } } if ( module == null || ! module . exists ( ) ) { String filepath = path . removeFirstSegments ( <NUM_LIT:1> ) . toString ( ) ; throw new IllegalArgumentException ( Services . getMessage ( "<STR_LIT>" , filepath , "<STR_LIT>" ) ) ; } return module ; } } </s>
|
<s> package org . eclim . plugin . dltk ; import org . eclim . Services ; import org . eclim . plugin . AbstractPluginResources ; public class PluginResources extends AbstractPluginResources { public static final String NAME = "<STR_LIT>" ; @ Override public void initialize ( String name ) { super . initialize ( name ) ; } protected String getBundleBaseName ( ) { return "<STR_LIT>" ; } } </s>
|
<s> package org . eclim . plugin . dltk . preference ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Map ; import org . apache . commons . lang . ArrayUtils ; import org . eclipse . dltk . launching . IInterpreterInstallType ; import org . eclipse . dltk . launching . ScriptRuntime ; public class DltkInterpreterTypeManager { private static Map < String , String > interpreterTypeAliases = new HashMap < String , String > ( ) ; public static void addInterpreterType ( String alias , String nature , String typeId ) { interpreterTypeAliases . put ( nature + '<CHAR_LIT:.>' + alias , typeId ) ; } public static IInterpreterInstallType getInterpreterInstallType ( String alias , String nature ) { String typeId = interpreterTypeAliases . get ( nature + '<CHAR_LIT:.>' + alias ) ; if ( typeId != null ) { IInterpreterInstallType [ ] types = ScriptRuntime . getInterpreterInstallTypes ( nature ) ; for ( IInterpreterInstallType iit : types ) { if ( typeId . equals ( iit . getId ( ) ) ) { return iit ; } } } return null ; } public static String [ ] getIntepreterTypeAliases ( String nature ) { ArrayList < String > aliases = new ArrayList < String > ( ) ; for ( String alias : interpreterTypeAliases . keySet ( ) ) { if ( alias . startsWith ( nature + '<CHAR_LIT:.>' ) ) { aliases . add ( alias ) ; } } return aliases . toArray ( ArrayUtils . EMPTY_STRING_ARRAY ) ; } } </s>
|
<s> package org . eclim . plugin . dltk . project ; import java . io . FileInputStream ; import java . util . ArrayList ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . eclim . Services ; import org . eclim . command . CommandLine ; import org . eclim . command . Error ; import org . eclim . command . Options ; import org . eclim . plugin . core . project . ProjectManager ; import org . eclim . plugin . core . util . ProjectUtils ; import org . eclim . plugin . core . util . XmlUtils ; import org . eclim . plugin . dltk . PluginResources ; import org . eclim . util . IOUtils ; import org . eclim . util . StringUtils ; import org . eclim . util . file . FileOffsets ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IResource ; import org . eclipse . dltk . core . DLTKCore ; import org . eclipse . dltk . core . IBuildpathEntry ; import org . eclipse . dltk . core . IDLTKLanguageToolkit ; import org . eclipse . dltk . core . IModelStatus ; import org . eclipse . dltk . core . IScriptProject ; import org . eclipse . dltk . core . SourceParserUtil ; import org . eclipse . dltk . internal . core . BuildpathEntry ; import org . eclipse . dltk . internal . ui . wizards . BuildpathDetector ; public abstract class DltkProjectManager implements ProjectManager { private static final String BUILDPATH = "<STR_LIT>" ; private static final String BUILDPATH_XSD = "<STR_LIT>" ; public void create ( IProject project , CommandLine commandLine ) throws Exception { String dependsString = commandLine . getValue ( Options . DEPENDS_OPTION ) ; IScriptProject scriptProject = DLTKCore . create ( project ) ; if ( ! project . getFile ( BUILDPATH ) . exists ( ) ) { IDLTKLanguageToolkit toolkit = getLanguageToolkit ( ) ; BuildpathDetector detector = new BuildpathDetector ( project , toolkit ) ; detector . detectBuildpath ( null ) ; IBuildpathEntry [ ] detected = detector . getBuildpath ( ) ; ArrayList < IBuildpathEntry > entries = new ArrayList < IBuildpathEntry > ( ) ; for ( IBuildpathEntry entry : detected ) { IModelStatus status = BuildpathEntry . validateBuildpathEntry ( scriptProject , entry , true ) ; if ( status . isOK ( ) ) { entries . add ( entry ) ; } } detected = entries . toArray ( new IBuildpathEntry [ entries . size ( ) ] ) ; IBuildpathEntry [ ] depends = createOrUpdateDependencies ( scriptProject , dependsString ) ; IBuildpathEntry [ ] buildpath = merge ( new IBuildpathEntry [ ] [ ] { detected , depends } ) ; scriptProject . setRawBuildpath ( buildpath , null ) ; } scriptProject . makeConsistent ( null ) ; scriptProject . save ( null , false ) ; } public List < Error > update ( IProject project , CommandLine commandLine ) throws Exception { IScriptProject scriptProject = DLTKCore . create ( project ) ; scriptProject . getResource ( ) . refreshLocal ( IResource . DEPTH_INFINITE , null ) ; PluginResources resources = ( PluginResources ) Services . getPluginResources ( PluginResources . NAME ) ; List < Error > errors = XmlUtils . validateXml ( scriptProject . getProject ( ) . getName ( ) , BUILDPATH , resources . getResource ( BUILDPATH_XSD ) . toString ( ) ) ; if ( errors . size ( ) > <NUM_LIT:0> ) { return errors ; } String dotbuildpath = scriptProject . getProject ( ) . getFile ( BUILDPATH ) . getRawLocation ( ) . toOSString ( ) ; IBuildpathEntry [ ] entries = scriptProject . readRawBuildpath ( ) ; FileOffsets offsets = FileOffsets . compile ( dotbuildpath ) ; String buildpath = IOUtils . toString ( new FileInputStream ( dotbuildpath ) ) ; errors = new ArrayList < Error > ( ) ; for ( IBuildpathEntry entry : entries ) { IModelStatus status = BuildpathEntry . validateBuildpathEntry ( scriptProject , entry , true ) ; if ( ! status . isOK ( ) ) { errors . add ( createErrorForEntry ( entry , status , offsets , dotbuildpath , buildpath ) ) ; } } scriptProject . setRawBuildpath ( entries , null ) ; scriptProject . makeConsistent ( null ) ; if ( errors . size ( ) > <NUM_LIT:0> ) { return errors ; } return null ; } public void delete ( IProject project , CommandLine commandLine ) throws Exception { } public void refresh ( IProject project , CommandLine commandLine ) throws Exception { SourceParserUtil . clearCache ( ) ; } public void refresh ( IProject project , IFile file ) throws Exception { } public abstract IDLTKLanguageToolkit getLanguageToolkit ( ) ; protected Error createErrorForEntry ( IBuildpathEntry entry , IModelStatus status , FileOffsets offsets , String filename , String contents ) throws Exception { int line = <NUM_LIT:1> ; int col = <NUM_LIT:1> ; String path = entry . getPath ( ) . toOSString ( ) ; Matcher matcher = Pattern . compile ( "<STR_LIT>" + path + "<STR_LIT>" ) . matcher ( contents ) ; if ( matcher . find ( ) ) { int [ ] position = offsets . offsetToLineColumn ( matcher . start ( ) ) ; line = position [ <NUM_LIT:0> ] ; col = position [ <NUM_LIT:1> ] ; } return new Error ( status . getMessage ( ) , filename , line , col , false ) ; } protected IBuildpathEntry [ ] createOrUpdateDependencies ( IScriptProject project , String depends ) throws Exception { if ( depends != null ) { String [ ] dependPaths = StringUtils . split ( depends , '<CHAR_LIT:U+002C>' ) ; IBuildpathEntry [ ] entries = new IBuildpathEntry [ dependPaths . length ] ; for ( int ii = <NUM_LIT:0> ; ii < dependPaths . length ; ii ++ ) { IProject theProject = ProjectUtils . getProject ( dependPaths [ ii ] ) ; if ( ! theProject . exists ( ) ) { throw new IllegalArgumentException ( Services . getMessage ( "<STR_LIT>" , dependPaths [ ii ] ) ) ; } IScriptProject otherProject = DLTKCore . create ( theProject ) ; entries [ ii ] = DLTKCore . newProjectEntry ( otherProject . getPath ( ) , true ) ; } return entries ; } return new IBuildpathEntry [ <NUM_LIT:0> ] ; } protected IBuildpathEntry [ ] merge ( IBuildpathEntry [ ] [ ] entries ) { ArrayList < IBuildpathEntry > union = new ArrayList < IBuildpathEntry > ( ) ; if ( entries != null ) { for ( IBuildpathEntry [ ] values : entries ) { if ( values != null ) { for ( IBuildpathEntry entry : values ) { if ( ! union . contains ( entry ) ) { union . add ( entry ) ; } } } } } return ( IBuildpathEntry [ ] ) union . toArray ( new IBuildpathEntry [ union . size ( ) ] ) ; } } </s>
|
<s> package org . eclim . plugin . dltk . command . buildpath ; import java . util . ArrayList ; import org . eclim . annotation . Command ; import org . eclim . command . CommandLine ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclipse . core . runtime . IPath ; import org . eclipse . dltk . core . DLTKCore ; @ Command ( name = "<STR_LIT>" ) public class BuildpathVariablesCommand extends AbstractCommand { public Object execute ( CommandLine commandLine ) throws Exception { ArrayList < BuildpathVariable > results = new ArrayList < BuildpathVariable > ( ) ; String [ ] names = DLTKCore . getBuildpathVariableNames ( ) ; for ( int ii = <NUM_LIT:0> ; ii < names . length ; ii ++ ) { IPath path = DLTKCore . getBuildpathVariable ( names [ ii ] ) ; if ( path != null ) { BuildpathVariable variable = new BuildpathVariable ( ) ; variable . setName ( names [ ii ] ) ; variable . setPath ( path . toOSString ( ) ) ; results . add ( variable ) ; } } return results ; } } </s>
|
<s> package org . eclim . plugin . dltk . command . buildpath ; import org . eclim . Services ; import org . eclim . annotation . Command ; import org . eclim . command . CommandLine ; import org . eclim . command . Options ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclipse . core . runtime . Path ; import org . eclipse . dltk . core . DLTKCore ; @ Command ( name = "<STR_LIT>" , options = "<STR_LIT>" + "<STR_LIT>" ) public class BuildpathVariableCreateCommand extends AbstractCommand { public Object execute ( CommandLine commandLine ) throws Exception { String name = commandLine . getValue ( Options . NAME_OPTION ) ; String path = commandLine . getValue ( Options . PATH_OPTION ) ; DLTKCore . setBuildpathVariable ( name , new Path ( path ) , null ) ; return Services . getMessage ( "<STR_LIT>" , name ) ; } } </s>
|
<s> package org . eclim . plugin . dltk . command . buildpath ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . eclim . annotation . Command ; import org . eclim . command . CommandLine ; import org . eclim . command . Options ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclim . plugin . core . util . ProjectUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . ResourcesPlugin ; import org . eclipse . dltk . core . DLTKCore ; import org . eclipse . dltk . core . IBuildpathEntry ; import org . eclipse . dltk . core . IScriptProject ; @ Command ( name = "<STR_LIT>" , options = "<STR_LIT>" ) public class BuildpathsCommand extends AbstractCommand { private static final String LOCAL_ENV = "<STR_LIT>" ; public Object execute ( CommandLine commandLine ) throws Exception { String projectName = commandLine . getValue ( Options . PROJECT_OPTION ) ; IProject project = ProjectUtils . getProject ( projectName ) ; IScriptProject scriptProject = DLTKCore . create ( project ) ; ArrayList < String > paths = new ArrayList < String > ( ) ; HashSet < IScriptProject > visited = new HashSet < IScriptProject > ( ) ; collect ( scriptProject , paths , visited ) ; return paths ; } private void collect ( IScriptProject scriptProject , List < String > paths , Set < IScriptProject > visited ) throws Exception { if ( visited . contains ( scriptProject ) ) { return ; } visited . add ( scriptProject ) ; IBuildpathEntry [ ] entries = scriptProject . getResolvedBuildpath ( true ) ; for ( IBuildpathEntry entry : entries ) { switch ( entry . getEntryKind ( ) ) { case IBuildpathEntry . BPE_CONTAINER : case IBuildpathEntry . BPE_LIBRARY : case IBuildpathEntry . BPE_VARIABLE : String path = entry . getPath ( ) . toOSString ( ) ; if ( path . startsWith ( LOCAL_ENV ) ) { path = path . replaceFirst ( LOCAL_ENV , "<STR_LIT>" ) ; } if ( ! paths . contains ( path ) ) { paths . add ( path ) ; } break ; case IBuildpathEntry . BPE_SOURCE : paths . add ( ProjectUtils . getFilePath ( scriptProject . getProject ( ) , entry . getPath ( ) . toOSString ( ) ) ) ; break ; case IBuildpathEntry . BPE_PROJECT : IProject project = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getProject ( entry . getPath ( ) . segment ( <NUM_LIT:0> ) ) ; if ( project != null ) { collect ( DLTKCore . create ( project ) , paths , visited ) ; } break ; } } } } </s>
|
<s> package org . eclim . plugin . dltk . command . buildpath ; public class BuildpathVariable implements Comparable < BuildpathVariable > { private String name ; private String path ; public String getName ( ) { return this . name ; } public void setName ( String name ) { this . name = name ; } public String getPath ( ) { return this . path ; } public void setPath ( String path ) { this . path = path ; } public int compareTo ( BuildpathVariable obj ) { if ( obj == this ) { return <NUM_LIT:0> ; } return this . getName ( ) . compareTo ( obj . getName ( ) ) ; } } </s>
|
<s> package org . eclim . plugin . dltk . command . buildpath ; import org . eclim . Services ; import org . eclim . annotation . Command ; import org . eclim . command . CommandLine ; import org . eclim . command . Options ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclipse . dltk . core . DLTKCore ; @ Command ( name = "<STR_LIT>" , options = "<STR_LIT>" ) public class BuildpathVariableDeleteCommand extends AbstractCommand { public Object execute ( CommandLine commandLine ) throws Exception { String name = commandLine . getValue ( Options . NAME_OPTION ) ; DLTKCore . removeBuildpathVariable ( name , null ) ; return Services . getMessage ( "<STR_LIT>" , name ) ; } } </s>
|
<s> package org . eclim . plugin . dltk . command . complete ; import java . text . Collator ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Comparator ; import java . util . Locale ; import org . eclim . command . CommandLine ; import org . eclim . command . Options ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclim . plugin . core . command . complete . CodeCompleteResult ; import org . eclim . plugin . core . util . ProjectUtils ; import org . eclim . plugin . dltk . util . DltkUtils ; import org . eclipse . core . resources . IFile ; import org . eclipse . dltk . core . ISourceModule ; import org . eclipse . dltk . ui . text . completion . IScriptCompletionProposal ; import org . eclipse . dltk . ui . text . completion . ScriptCompletionProposalCollector ; public abstract class AbstractCodeCompleteCommand extends AbstractCommand { public Object execute ( CommandLine commandLine ) throws Exception { String project = commandLine . getValue ( Options . PROJECT_OPTION ) ; String file = commandLine . getValue ( Options . FILE_OPTION ) ; IFile ifile = ProjectUtils . getFile ( project , file ) ; int offset = getOffset ( commandLine ) ; int timeout = <NUM_LIT> ; ISourceModule module = getSourceModule ( ifile ) ; ScriptCompletionProposalCollector collector = getCompletionCollector ( module ) ; module . codeComplete ( offset , collector , timeout ) ; IScriptCompletionProposal [ ] proposals = collector . getScriptCompletionProposals ( ) ; Arrays . sort ( proposals , new ScriptCompletionProposalComparator ( ) ) ; ArrayList < CodeCompleteResult > results = new ArrayList < CodeCompleteResult > ( ) ; for ( IScriptCompletionProposal proposal : proposals ) { CodeCompleteResult ccresult = new CodeCompleteResult ( getCompletion ( proposal ) , getMenu ( proposal ) , getInfo ( proposal ) ) ; if ( ! results . contains ( ccresult ) ) { results . add ( ccresult ) ; } } return results ; } protected ISourceModule getSourceModule ( IFile file ) throws Exception { return DltkUtils . getSourceModule ( file ) ; } protected abstract ScriptCompletionProposalCollector getCompletionCollector ( ISourceModule module ) throws Exception ; protected String getCompletion ( IScriptCompletionProposal proposal ) { return proposal . getDisplayString ( ) . trim ( ) ; } protected String getMenu ( IScriptCompletionProposal proposal ) { return proposal . getDisplayString ( ) . trim ( ) ; } protected String getInfo ( IScriptCompletionProposal proposal ) { String info = proposal . getAdditionalProposalInfo ( ) ; if ( info != null ) { info = info . trim ( ) ; } return info ; } private class ScriptCompletionProposalComparator implements Comparator < IScriptCompletionProposal > { private Collator COLLATOR = Collator . getInstance ( Locale . US ) ; public int compare ( IScriptCompletionProposal p1 , IScriptCompletionProposal p2 ) { int diff = p1 . getRelevance ( ) - p2 . getRelevance ( ) ; if ( diff == <NUM_LIT:0> ) { return COLLATOR . compare ( getCompletion ( p1 ) , getCompletion ( p2 ) ) ; } return <NUM_LIT:0> - diff ; } } } </s>
|
<s> package org . eclim . plugin . dltk . command . launching ; import java . util . ArrayList ; import org . eclim . Services ; import org . eclim . annotation . Command ; import org . eclim . command . CommandLine ; import org . eclim . command . Options ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclim . plugin . core . project . ProjectNatureFactory ; import org . eclipse . core . runtime . Path ; import org . eclipse . dltk . core . environment . EnvironmentManager ; import org . eclipse . dltk . core . environment . IEnvironment ; import org . eclipse . dltk . core . environment . IFileHandle ; import org . eclipse . dltk . debug . ui . interpreters . InterpretersUpdater ; import org . eclipse . dltk . launching . IInterpreterInstall ; import org . eclipse . dltk . launching . IInterpreterInstallType ; import org . eclipse . dltk . launching . ScriptRuntime ; import org . eclipse . dltk . utils . PlatformFileUtils ; @ Command ( name = "<STR_LIT>" , options = "<STR_LIT>" + "<STR_LIT>" ) public class DeleteInterpreterCommand extends AbstractCommand { public Object execute ( CommandLine commandLine ) throws Exception { String nature = commandLine . getValue ( Options . NATURE_OPTION ) ; nature = ProjectNatureFactory . getNatureForAlias ( nature ) ; if ( nature == null ) { throw new RuntimeException ( Services . getMessage ( "<STR_LIT>" , commandLine . getValue ( Options . NATURE_OPTION ) ) ) ; } String interpreterPath = commandLine . getValue ( "<STR_LIT:i>" ) ; IEnvironment env = EnvironmentManager . getLocalEnvironment ( ) ; IFileHandle file = PlatformFileUtils . findAbsoluteOrEclipseRelativeFile ( env , new Path ( interpreterPath ) ) ; IInterpreterInstall deflt = ScriptRuntime . getDefaultInterpreterInstall ( new ScriptRuntime . DefaultInterpreterEntry ( nature , env . getId ( ) ) ) ; if ( deflt != null && deflt . getInstallLocation ( ) . equals ( file ) ) { deflt = null ; } IInterpreterInstallType [ ] types = ScriptRuntime . getInterpreterInstallTypes ( nature ) ; boolean removed = false ; ArrayList < IInterpreterInstall > interpreters = new ArrayList < IInterpreterInstall > ( ) ; for ( IInterpreterInstallType iit : types ) { IInterpreterInstall [ ] installs = iit . getInterpreterInstalls ( ) ; for ( IInterpreterInstall install : installs ) { if ( ! install . getInstallLocation ( ) . toOSString ( ) . equals ( file . toOSString ( ) ) ) { interpreters . add ( install ) ; } else { removed = true ; } } } IInterpreterInstall [ ] defaults = deflt != null ? new IInterpreterInstall [ ] { deflt } : null ; IInterpreterInstall [ ] installs = interpreters . toArray ( new IInterpreterInstall [ interpreters . size ( ) ] ) ; InterpretersUpdater updater = new InterpretersUpdater ( ) ; updater . updateInterpreterSettings ( nature , installs , defaults ) ; if ( removed ) { return Services . getMessage ( "<STR_LIT>" ) ; } return Services . getMessage ( "<STR_LIT>" ) ; } } </s>
|
<s> package org . eclim . plugin . dltk . command . launching ; import java . util . ArrayList ; import org . eclim . Services ; import org . eclim . annotation . Command ; import org . eclim . command . CommandLine ; import org . eclim . command . Options ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclim . plugin . core . project . ProjectNatureFactory ; import org . eclim . plugin . dltk . preference . DltkInterpreterTypeManager ; import org . eclipse . core . runtime . IPath ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . core . runtime . Path ; import org . eclipse . dltk . core . environment . EnvironmentManager ; import org . eclipse . dltk . core . environment . IEnvironment ; import org . eclipse . dltk . core . environment . IFileHandle ; import org . eclipse . dltk . core . internal . environment . LazyFileHandle ; import org . eclipse . dltk . debug . ui . interpreters . InterpretersUpdater ; import org . eclipse . dltk . internal . debug . ui . interpreters . EnvironmentVariableContentProvider ; import org . eclipse . dltk . launching . EnvironmentVariable ; import org . eclipse . dltk . launching . IInterpreterInstall ; import org . eclipse . dltk . launching . IInterpreterInstallType ; import org . eclipse . dltk . launching . InterpreterStandin ; import org . eclipse . dltk . launching . LibraryLocation ; import org . eclipse . dltk . launching . ScriptRuntime ; import org . eclipse . dltk . utils . PlatformFileUtils ; @ Command ( name = "<STR_LIT>" , options = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) public class AddInterpreterCommand extends AbstractCommand { public Object execute ( CommandLine commandLine ) throws Exception { String nature = commandLine . getValue ( Options . NATURE_OPTION ) ; nature = ProjectNatureFactory . getNatureForAlias ( nature ) ; if ( nature == null ) { throw new RuntimeException ( Services . getMessage ( "<STR_LIT>" , commandLine . getValue ( Options . NATURE_OPTION ) ) ) ; } String interpreterPath = commandLine . getValue ( "<STR_LIT:i>" ) ; IInterpreterInstallType type = getInterpreterInstallType ( nature , commandLine ) ; if ( type == null ) { throw new RuntimeException ( Services . getMessage ( "<STR_LIT>" ) ) ; } IEnvironment env = EnvironmentManager . getLocalEnvironment ( ) ; IFileHandle file = PlatformFileUtils . findAbsoluteOrEclipseRelativeFile ( env , new Path ( interpreterPath ) ) ; if ( ! file . exists ( ) ) { throw new RuntimeException ( Services . getMessage ( "<STR_LIT>" , interpreterPath ) ) ; } EnvironmentVariableContentProvider envVarsProvider = new EnvironmentVariableContentProvider ( ) ; EnvironmentVariable [ ] envVars = envVarsProvider . getVariables ( ) ; LibraryLocation [ ] libs = type . getDefaultLibraryLocations ( file , envVars , new NullProgressMonitor ( ) ) ; IStatus status = type . validateInstallLocation ( file , envVars , libs , new NullProgressMonitor ( ) ) ; if ( ! status . isOK ( ) ) { throw new RuntimeException ( status . getMessage ( ) ) ; } IInterpreterInstall deflt = ScriptRuntime . getDefaultInterpreterInstall ( new ScriptRuntime . DefaultInterpreterEntry ( nature , env . getId ( ) ) ) ; if ( deflt != null && deflt . getInstallLocation ( ) . equals ( file ) ) { throw new RuntimeException ( Services . getMessage ( "<STR_LIT>" , interpreterPath ) ) ; } ArrayList < IInterpreterInstall > interpreters = new ArrayList < IInterpreterInstall > ( ) ; IInterpreterInstallType [ ] types = ScriptRuntime . getInterpreterInstallTypes ( nature ) ; for ( IInterpreterInstallType iit : types ) { IInterpreterInstall [ ] installs = iit . getInterpreterInstalls ( ) ; for ( IInterpreterInstall install : installs ) { if ( install . getInstallLocation ( ) . equals ( file ) ) { throw new RuntimeException ( Services . getMessage ( "<STR_LIT>" , interpreterPath ) ) ; } interpreters . add ( install ) ; } } String name = generateInterpreterName ( file , nature ) ; String id = null ; do { id = String . valueOf ( System . currentTimeMillis ( ) ) ; } while ( type . findInterpreterInstall ( id ) != null ) ; IInterpreterInstall install = new InterpreterStandin ( type , id ) ; install . setInstallLocation ( new LazyFileHandle ( env . getId ( ) , new Path ( interpreterPath ) ) ) ; install . setName ( name ) ; install . setLibraryLocations ( libs ) ; install . setInterpreterArgs ( null ) ; install = ( ( InterpreterStandin ) install ) . convertToRealInterpreter ( ) ; interpreters . add ( install ) ; if ( deflt == null ) { deflt = install ; ScriptRuntime . setDefaultInterpreterInstall ( install , null , false ) ; } IInterpreterInstall [ ] defaults = { deflt } ; IInterpreterInstall [ ] installs = interpreters . toArray ( new IInterpreterInstall [ interpreters . size ( ) ] ) ; InterpretersUpdater updater = new InterpretersUpdater ( ) ; updater . updateInterpreterSettings ( nature , installs , defaults ) ; return Services . getMessage ( "<STR_LIT>" ) ; } protected IInterpreterInstallType getInterpreterInstallType ( String nature , CommandLine commandLine ) throws Exception { String interpreterType = commandLine . getValue ( Options . TYPE_OPTION ) ; return DltkInterpreterTypeManager . getInterpreterInstallType ( interpreterType , nature ) ; } protected String generateInterpreterName ( IFileHandle file , String nature ) { final String genName ; final IPath path = new Path ( file . getCanonicalPath ( ) ) ; if ( path . segmentCount ( ) > <NUM_LIT:0> ) { genName = path . lastSegment ( ) ; } else { genName = null ; } String name = genName ; if ( name != null ) { int index = <NUM_LIT:0> ; while ( ! validateGeneratedName ( name , nature ) ) { name = genName + "<STR_LIT:(>" + String . valueOf ( ++ index ) + "<STR_LIT:)>" ; } } return name ; } protected boolean validateGeneratedName ( String name , String nature ) { IInterpreterInstallType [ ] types = ScriptRuntime . getInterpreterInstallTypes ( nature ) ; for ( IInterpreterInstallType type : types ) { IInterpreterInstall install = type . findInterpreterInstallByName ( name ) ; if ( install != null ) { return false ; } } return true ; } } </s>
|
<s> package org . eclim . plugin . dltk . command . launching ; import java . util . ArrayList ; import java . util . HashMap ; import org . eclim . Services ; import org . eclim . annotation . Command ; import org . eclim . command . CommandLine ; import org . eclim . command . Options ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclim . plugin . core . project . ProjectNatureFactory ; import org . eclim . plugin . core . util . ProjectUtils ; import org . eclim . plugin . dltk . util . DltkUtils ; import org . eclipse . core . resources . IProject ; import org . eclipse . dltk . core . environment . EnvironmentManager ; import org . eclipse . dltk . core . environment . IEnvironment ; import org . eclipse . dltk . launching . IInterpreterInstall ; import org . eclipse . dltk . launching . IInterpreterInstallType ; import org . eclipse . dltk . launching . ScriptRuntime ; @ Command ( name = "<STR_LIT>" , options = "<STR_LIT>" + "<STR_LIT>" ) public class InterpretersCommand extends AbstractCommand { public Object execute ( CommandLine commandLine ) throws Exception { String projectName = commandLine . getValue ( Options . PROJECT_OPTION ) ; String nature = commandLine . getValue ( Options . NATURE_OPTION ) ; if ( projectName == null && nature == null ) { throw new RuntimeException ( Services . getMessage ( "<STR_LIT>" ) ) ; } IEnvironment env = null ; ArrayList < String > natures = new ArrayList < String > ( ) ; if ( projectName != null ) { IProject project = ProjectUtils . getProject ( projectName , true ) ; env = EnvironmentManager . getEnvironment ( project ) ; for ( String n : DltkUtils . getDltkNatures ( ) ) { if ( project . hasNature ( n ) ) { natures . add ( n ) ; } } } else { nature = ProjectNatureFactory . getNatureForAlias ( nature ) ; if ( nature == null ) { throw new RuntimeException ( Services . getMessage ( "<STR_LIT>" , commandLine . getValue ( Options . NATURE_OPTION ) ) ) ; } natures . add ( nature ) ; env = EnvironmentManager . getLocalEnvironment ( ) ; } ArrayList < HashMap < String , Object > > interpreters = new ArrayList < HashMap < String , Object > > ( ) ; for ( String natureId : natures ) { IInterpreterInstall deflt = ScriptRuntime . getDefaultInterpreterInstall ( new ScriptRuntime . DefaultInterpreterEntry ( natureId , env . getId ( ) ) ) ; if ( deflt != null ) { HashMap < String , Object > defaultInt = new HashMap < String , Object > ( ) ; defaultInt . put ( "<STR_LIT>" , ProjectNatureFactory . getAliasForNature ( natureId ) ) ; defaultInt . put ( "<STR_LIT:name>" , deflt . getName ( ) ) ; defaultInt . put ( "<STR_LIT:path>" , deflt . getInstallLocation ( ) . getPath ( ) . toOSString ( ) ) ; defaultInt . put ( "<STR_LIT:default>" , true ) ; interpreters . add ( defaultInt ) ; } IInterpreterInstallType [ ] types = ScriptRuntime . getInterpreterInstallTypes ( natureId ) ; for ( IInterpreterInstallType type : types ) { IInterpreterInstall [ ] installs = type . getInterpreterInstalls ( ) ; for ( IInterpreterInstall install : installs ) { if ( ! install . equals ( deflt ) ) { HashMap < String , Object > inter = new HashMap < String , Object > ( ) ; inter . put ( "<STR_LIT>" , ProjectNatureFactory . getAliasForNature ( natureId ) ) ; inter . put ( "<STR_LIT:name>" , install . getName ( ) ) ; inter . put ( "<STR_LIT:path>" , install . getInstallLocation ( ) . getPath ( ) . toOSString ( ) ) ; inter . put ( "<STR_LIT:default>" , false ) ; interpreters . add ( inter ) ; } } } } return interpreters ; } } </s>
|
<s> package org . eclim . plugin . dltk . command . src ; import java . util . ArrayList ; import java . util . List ; import org . eclim . command . CommandLine ; import org . eclim . command . Error ; import org . eclim . command . Options ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclim . plugin . core . util . ProjectUtils ; import org . eclim . plugin . dltk . util . DltkUtils ; import org . eclim . util . file . FileOffsets ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . resources . IncrementalProjectBuilder ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . dltk . ast . parser . ISourceParser ; import org . eclipse . dltk . ast . parser . SourceParserManager ; import org . eclipse . dltk . compiler . env . IModuleSource ; import org . eclipse . dltk . compiler . problem . AbstractProblemReporter ; import org . eclipse . dltk . compiler . problem . IProblem ; public abstract class AbstractSrcUpdateCommand extends AbstractCommand { public Object execute ( CommandLine commandLine ) throws Exception { String file = commandLine . getValue ( Options . FILE_OPTION ) ; String projectName = commandLine . getValue ( Options . PROJECT_OPTION ) ; IProject project = ProjectUtils . getProject ( projectName , true ) ; IFile ifile = ProjectUtils . getFile ( project , file ) ; if ( commandLine . hasOption ( Options . VALIDATE_OPTION ) ) { Reporter reporter = new Reporter ( ) ; parse ( project , ifile , reporter ) ; String filepath = ProjectUtils . getFilePath ( project , file ) ; FileOffsets offsets = FileOffsets . compile ( filepath ) ; ArrayList < Error > errors = new ArrayList < Error > ( ) ; for ( IProblem problem : reporter . getProblems ( ) ) { int [ ] lineColumn = offsets . offsetToLineColumn ( problem . getSourceStart ( ) ) ; errors . add ( new Error ( problem . getMessage ( ) , filepath , lineColumn [ <NUM_LIT:0> ] , lineColumn [ <NUM_LIT:1> ] , problem . isWarning ( ) ) ) ; } if ( commandLine . hasOption ( Options . BUILD_OPTION ) ) { project . build ( IncrementalProjectBuilder . INCREMENTAL_BUILD , new NullProgressMonitor ( ) ) ; } return errors ; } return null ; } protected void parse ( IProject project , IFile file , Reporter reporter ) throws Exception { IModuleSource module = ( IModuleSource ) DltkUtils . getSourceModule ( file ) ; ISourceParser parser = SourceParserManager . getInstance ( ) . getSourceParser ( project , getNature ( ) ) ; parser . parse ( module , reporter ) ; } protected abstract String getNature ( ) ; protected class Reporter extends AbstractProblemReporter { private List < IProblem > problems = new ArrayList < IProblem > ( ) ; public void reportProblem ( IProblem problem ) { problems . add ( problem ) ; } public List < IProblem > getProblems ( ) { return problems ; } } } </s>
|
<s> package org . eclim . plugin . dltk . command . search ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import org . apache . commons . lang . StringUtils ; import org . eclim . annotation . Command ; import org . eclim . command . CommandLine ; import org . eclim . command . Options ; import org . eclim . plugin . core . command . AbstractCommand ; import org . eclim . plugin . core . project . ProjectManagement ; import org . eclim . plugin . core . project . ProjectManager ; import org . eclim . plugin . core . util . ProjectUtils ; import org . eclim . plugin . dltk . project . DltkProjectManager ; import org . eclim . util . file . Position ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IProject ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . NullProgressMonitor ; import org . eclipse . dltk . core . DLTKCore ; import org . eclipse . dltk . core . IDLTKLanguageToolkit ; import org . eclipse . dltk . core . IModelElement ; import org . eclipse . dltk . core . ISourceModule ; import org . eclipse . dltk . core . search . IDLTKSearchConstants ; import org . eclipse . dltk . core . search . IDLTKSearchScope ; import org . eclipse . dltk . core . search . SearchEngine ; import org . eclipse . dltk . core . search . SearchMatch ; import org . eclipse . dltk . core . search . SearchParticipant ; import org . eclipse . dltk . core . search . SearchPattern ; import org . eclipse . dltk . internal . corext . util . SearchUtils ; import org . eclipse . dltk . internal . ui . search . DLTKSearchScopeFactory ; @ Command ( name = "<STR_LIT>" , options = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) public class SearchCommand extends AbstractCommand { public static final String CONTEXT_ALL = "<STR_LIT:all>" ; public static final String CONTEXT_DECLARATIONS = "<STR_LIT>" ; public static final String CONTEXT_REFERENCES = "<STR_LIT>" ; public static final String SCOPE_ALL = "<STR_LIT:all>" ; public static final String SCOPE_PROJECT = "<STR_LIT>" ; public static final String TYPE_CLASS = "<STR_LIT:class>" ; public static final String TYPE_METHOD = "<STR_LIT>" ; public static final String TYPE_FUNCTION = "<STR_LIT>" ; public static final String TYPE_FIELD = "<STR_LIT:field>" ; @ Override public Object execute ( CommandLine commandLine ) throws Exception { String projectName = commandLine . getValue ( Options . NAME_OPTION ) ; String file = commandLine . getValue ( Options . FILE_OPTION ) ; String offset = commandLine . getValue ( Options . OFFSET_OPTION ) ; String length = commandLine . getValue ( Options . LENGTH_OPTION ) ; String pattern = commandLine . getValue ( Options . PATTERN_OPTION ) ; int type = getType ( commandLine . getValue ( Options . TYPE_OPTION ) ) ; int context = getContext ( commandLine . getValue ( Options . CONTEXT_OPTION ) ) ; IProject project = projectName != null ? ProjectUtils . getProject ( projectName ) : null ; IDLTKSearchScope scope = getScope ( commandLine . getValue ( Options . SCOPE_OPTION ) , type , project ) ; SearchEngine engine = new SearchEngine ( ) ; IDLTKLanguageToolkit toolkit = scope . getLanguageToolkit ( ) ; SearchPattern searchPattern = null ; if ( file != null && offset != null && length != null ) { IFile ifile = ProjectUtils . getFile ( project , file ) ; ISourceModule src = DLTKCore . createSourceModuleFrom ( ifile ) ; IModelElement [ ] elements = getElements ( src , getOffset ( commandLine ) , Integer . parseInt ( length ) ) ; IModelElement element = null ; if ( elements != null && elements . length > <NUM_LIT:0> ) { element = elements [ <NUM_LIT:0> ] ; } if ( element != null && element . exists ( ) ) { searchPattern = SearchPattern . createPattern ( element , context , SearchUtils . GENERICS_AGNOSTIC_MATCH_RULE , toolkit ) ; } } else { int mode = getMode ( pattern ) | SearchPattern . R_ERASURE_MATCH ; boolean caseSensitive = ! commandLine . hasOption ( Options . CASE_INSENSITIVE_OPTION ) ; if ( caseSensitive ) { mode |= SearchPattern . R_CASE_SENSITIVE ; } if ( type == IDLTKSearchConstants . UNKNOWN ) { SearchPattern byType = SearchPattern . createPattern ( pattern , IDLTKSearchConstants . TYPE , context , mode , toolkit ) ; SearchPattern byMethod = SearchPattern . createPattern ( pattern , IDLTKSearchConstants . METHOD , context , mode , toolkit ) ; SearchPattern byField = SearchPattern . createPattern ( pattern , IDLTKSearchConstants . FIELD , context , mode , toolkit ) ; searchPattern = SearchPattern . createOrPattern ( byType , SearchPattern . createOrPattern ( byMethod , byField ) ) ; } else { searchPattern = SearchPattern . createPattern ( pattern , type , context , mode , toolkit ) ; } } if ( searchPattern != null ) { SearchRequestor requestor = new SearchRequestor ( ) ; engine . search ( searchPattern , new SearchParticipant [ ] { SearchEngine . getDefaultSearchParticipant ( ) } , scope , requestor , new NullProgressMonitor ( ) ) ; return requestor . getMatches ( ) ; } return null ; } protected IModelElement [ ] getElements ( ISourceModule src , int offset , int length ) throws Exception { return src . codeSelect ( offset , length ) ; } protected IDLTKSearchScope getScope ( String scope , int type , IProject project ) throws Exception { boolean includeInterpreterEnvironment = false ; DLTKSearchScopeFactory factory = DLTKSearchScopeFactory . getInstance ( ) ; IDLTKLanguageToolkit toolkit = null ; ProjectManager manager = ProjectManagement . getProjectManager ( getNature ( ) ) ; if ( manager instanceof DltkProjectManager ) { toolkit = ( ( DltkProjectManager ) manager ) . getLanguageToolkit ( ) ; } if ( toolkit == null && project != null ) { for ( String nature : ProjectManagement . getProjectManagerNatures ( ) ) { if ( project . hasNature ( nature ) ) { manager = ProjectManagement . getProjectManager ( nature ) ; if ( manager instanceof DltkProjectManager ) { toolkit = ( ( DltkProjectManager ) manager ) . getLanguageToolkit ( ) ; break ; } } } } IDLTKSearchScope searchScope = null ; if ( SCOPE_PROJECT . equals ( scope ) ) { String [ ] names = new String [ ] { project . getName ( ) } ; searchScope = factory . createProjectSearchScope ( names , includeInterpreterEnvironment , toolkit ) ; } else { searchScope = factory . createWorkspaceScope ( includeInterpreterEnvironment , toolkit ) ; } return searchScope ; } protected String getNature ( ) { return null ; } protected int getContext ( String context ) { if ( CONTEXT_ALL . equals ( context ) ) { return IDLTKSearchConstants . ALL_OCCURRENCES ; } else if ( CONTEXT_REFERENCES . equals ( context ) ) { return IDLTKSearchConstants . REFERENCES ; } return IDLTKSearchConstants . DECLARATIONS ; } protected int getType ( String type ) { if ( TYPE_CLASS . equals ( type ) ) { return IDLTKSearchConstants . TYPE ; } else if ( TYPE_METHOD . equals ( type ) || TYPE_FUNCTION . equals ( type ) ) { return IDLTKSearchConstants . METHOD ; } else if ( TYPE_FIELD . equals ( type ) ) { return IDLTKSearchConstants . FIELD ; } return IDLTKSearchConstants . UNKNOWN ; } private int getMode ( String pattern ) { if ( pattern . indexOf ( '<CHAR_LIT>' ) != - <NUM_LIT:1> || pattern . indexOf ( '<CHAR_LIT>' ) != - <NUM_LIT:1> ) { return SearchPattern . R_PATTERN_MATCH ; } if ( SearchUtils . isCamelCasePattern ( pattern ) ) { return SearchPattern . R_CAMELCASE_MATCH ; } return SearchPattern . R_EXACT_MATCH ; } protected String getElement ( Object el ) { IModelElement element = ( IModelElement ) el ; ArrayList < IModelElement > lineage = new ArrayList < IModelElement > ( ) ; while ( element . getElementType ( ) != IModelElement . SOURCE_MODULE ) { lineage . add ( <NUM_LIT:0> , element ) ; element = element . getParent ( ) ; } StringBuffer fullyQualified = new StringBuffer ( ) ; for ( IModelElement e : lineage ) { if ( fullyQualified . length ( ) != <NUM_LIT:0> ) { fullyQualified . append ( getElementSeparator ( ) ) ; } if ( e . getElementType ( ) == IModelElement . TYPE ) { fullyQualified . append ( getElementTypeName ( ) ) . append ( '<CHAR_LIT:U+0020>' ) ; } if ( e . getElementType ( ) == IModelElement . FIELD ) { fullyQualified . append ( getElementFieldName ( ) ) . append ( '<CHAR_LIT:U+0020>' ) ; } if ( e . getElementType ( ) == IModelElement . METHOD ) { if ( e . getParent ( ) . getElementType ( ) == IModelElement . TYPE ) { fullyQualified . append ( getElementMethodName ( ) ) . append ( '<CHAR_LIT:U+0020>' ) ; } else { fullyQualified . append ( getElementFunctionName ( ) ) . append ( '<CHAR_LIT:U+0020>' ) ; } } fullyQualified . append ( e . getElementName ( ) ) ; } return fullyQualified . toString ( ) ; } protected String getElementSeparator ( ) { return "<STR_LIT:U+0020>" ; } protected String getElementTypeName ( ) { return "<STR_LIT:type>" ; } protected String getElementFieldName ( ) { return "<STR_LIT:field>" ; } protected String getElementMethodName ( ) { return "<STR_LIT>" ; } protected String getElementFunctionName ( ) { return "<STR_LIT>" ; } private class SearchRequestor extends org . eclipse . dltk . core . search . SearchRequestor { private ArrayList < Position > matches = new ArrayList < Position > ( ) ; @ Override public void acceptSearchMatch ( SearchMatch match ) throws CoreException { if ( match . getAccuracy ( ) == SearchMatch . A_ACCURATE ) { IModelElement element = ( IModelElement ) match . getElement ( ) ; ArrayList < IModelElement > lineage = new ArrayList < IModelElement > ( ) ; while ( element . getElementType ( ) != IModelElement . SOURCE_MODULE ) { lineage . add ( <NUM_LIT:0> , element ) ; element = element . getParent ( ) ; } StringBuffer fullyQualified = new StringBuffer ( ) ; for ( IModelElement el : lineage ) { if ( fullyQualified . length ( ) != <NUM_LIT:0> ) { fullyQualified . append ( "<STR_LIT>" ) ; } if ( el . getElementType ( ) == IModelElement . TYPE ) { fullyQualified . append ( "<STR_LIT>" ) ; } if ( el . getElementType ( ) == IModelElement . METHOD ) { fullyQualified . append ( "<STR_LIT>" ) ; } fullyQualified . append ( el . getElementName ( ) ) ; } String filename = match . getResource ( ) . getLocation ( ) . toOSString ( ) . replace ( '<STR_LIT:\\>' , '<CHAR_LIT:/>' ) ; File file = new File ( filename ) ; if ( ! file . exists ( ) || ! file . isFile ( ) ) { return ; } Position position = Position . fromOffset ( filename , StringUtils . EMPTY , match . getOffset ( ) , match . getLength ( ) ) ; int index = matches . indexOf ( position ) ; String name = SearchCommand . this . getElement ( match . getElement ( ) ) ; if ( index == - <NUM_LIT:1> ) { position . setMessage ( name ) ; if ( ! matches . contains ( position ) ) { matches . add ( position ) ; } } else if ( ! StringUtils . EMPTY . equals ( name ) ) { position = matches . get ( index ) ; position . setMessage ( name ) ; } } } public List < Position > getMatches ( ) { return matches ; } } } </s>
|
<s> package com . classicnerd . ClassicnerdWallpapers ; import android . app . Activity ; import android . content . res . Resources ; import android . graphics . BitmapFactory ; import android . graphics . Bitmap ; import android . graphics . drawable . Drawable ; import android . os . Bundle ; import android . os . AsyncTask ; import android . util . Log ; import android . view . LayoutInflater ; import android . view . View ; import android . view . ViewGroup ; import android . view . Window ; import android . view . View . OnClickListener ; import android . widget . AdapterView ; import android . widget . BaseAdapter ; import android . widget . Gallery ; import android . widget . ImageView ; import java . io . IOException ; import java . io . InputStream ; import java . util . ArrayList ; public class wallpaper extends Activity implements AdapterView . OnItemSelectedListener , OnClickListener { private Gallery mGallery ; private ImageView mImageView ; private boolean mIsWallpaperSet ; private Bitmap mBitmap ; private ArrayList < Integer > mThumbs ; private ArrayList < Integer > mImages ; private WallpaperLoader mLoader ; @ Override public void onCreate ( Bundle icicle ) { super . onCreate ( icicle ) ; requestWindowFeature ( Window . FEATURE_NO_TITLE ) ; findWallpapers ( ) ; setContentView ( R . layout . wallpaper_chooser ) ; mGallery = ( Gallery ) findViewById ( R . id . gallery ) ; mGallery . setAdapter ( new ImageAdapter ( this ) ) ; mGallery . setOnItemSelectedListener ( this ) ; mGallery . setCallbackDuringFling ( false ) ; findViewById ( R . id . set ) . setOnClickListener ( this ) ; mImageView = ( ImageView ) findViewById ( R . id . wallpaper ) ; } private void findWallpapers ( ) { mThumbs = new ArrayList < Integer > ( <NUM_LIT:24> ) ; mImages = new ArrayList < Integer > ( <NUM_LIT:24> ) ; final Resources resources = getResources ( ) ; final String packageName = getApplication ( ) . getPackageName ( ) ; addWallpapers ( resources , packageName , R . array . wallpapers ) ; addWallpapers ( resources , packageName , R . array . extra_wallpapers ) ; } private void addWallpapers ( Resources resources , String packageName , int list ) { final String [ ] extras = resources . getStringArray ( list ) ; for ( String extra : extras ) { int res = resources . getIdentifier ( extra , "<STR_LIT>" , packageName ) ; if ( res != <NUM_LIT:0> ) { final int thumbRes = resources . getIdentifier ( extra + "<STR_LIT>" , "<STR_LIT>" , packageName ) ; if ( thumbRes != <NUM_LIT:0> ) { mThumbs . add ( thumbRes ) ; mImages . add ( res ) ; } } } } @ Override protected void onResume ( ) { super . onResume ( ) ; mIsWallpaperSet = false ; } @ Override protected void onDestroy ( ) { super . onDestroy ( ) ; if ( mLoader != null && mLoader . getStatus ( ) != WallpaperLoader . Status . FINISHED ) { mLoader . cancel ( true ) ; mLoader = null ; } } public void onItemSelected ( AdapterView parent , View v , int position , long id ) { if ( mLoader != null && mLoader . getStatus ( ) != WallpaperLoader . Status . FINISHED ) { mLoader . cancel ( ) ; } mLoader = ( WallpaperLoader ) new WallpaperLoader ( ) . execute ( position ) ; } private void selectWallpaper ( int position ) { if ( mIsWallpaperSet ) { return ; } mIsWallpaperSet = true ; try { InputStream stream = getResources ( ) . openRawResource ( mImages . get ( position ) ) ; setWallpaper ( stream ) ; setResult ( RESULT_OK ) ; finish ( ) ; } catch ( IOException e ) { Log . e ( "<STR_LIT>" , "<STR_LIT>" + e ) ; } } public void onNothingSelected ( AdapterView parent ) { } private class ImageAdapter extends BaseAdapter { private LayoutInflater mLayoutInflater ; ImageAdapter ( wallpaper context ) { mLayoutInflater = context . getLayoutInflater ( ) ; } public int getCount ( ) { return mThumbs . size ( ) ; } public Object getItem ( int position ) { return position ; } public long getItemId ( int position ) { return position ; } public View getView ( int position , View convertView , ViewGroup parent ) { ImageView image ; if ( convertView == null ) { image = ( ImageView ) mLayoutInflater . inflate ( R . layout . wallpaper_item , parent , false ) ; } else { image = ( ImageView ) convertView ; } int thumbRes = mThumbs . get ( position ) ; image . setImageResource ( thumbRes ) ; Drawable thumbDrawable = image . getDrawable ( ) ; if ( thumbDrawable != null ) { thumbDrawable . setDither ( true ) ; } else { Log . e ( "<STR_LIT>" , String . format ( "<STR_LIT>" , thumbRes , position ) ) ; } return image ; } } public void onClick ( View v ) { selectWallpaper ( mGallery . getSelectedItemPosition ( ) ) ; } class WallpaperLoader extends AsyncTask < Integer , Void , Bitmap > { BitmapFactory . Options mOptions ; WallpaperLoader ( ) { mOptions = new BitmapFactory . Options ( ) ; mOptions . inDither = false ; mOptions . inPreferredConfig = Bitmap . Config . ARGB_8888 ; } protected Bitmap doInBackground ( Integer ... params ) { if ( isCancelled ( ) ) return null ; try { return BitmapFactory . decodeResource ( getResources ( ) , mImages . get ( params [ <NUM_LIT:0> ] ) , mOptions ) ; } catch ( OutOfMemoryError e ) { return null ; } } @ Override protected void onPostExecute ( Bitmap b ) { if ( b == null ) return ; if ( ! isCancelled ( ) && ! mOptions . mCancel ) { if ( mBitmap != null ) { mBitmap . recycle ( ) ; } final ImageView view = mImageView ; view . setImageBitmap ( b ) ; mBitmap = b ; final Drawable drawable = view . getDrawable ( ) ; drawable . setFilterBitmap ( true ) ; drawable . setDither ( true ) ; view . postInvalidate ( ) ; mLoader = null ; } else { b . recycle ( ) ; } } void cancel ( ) { mOptions . requestCancelDecode ( ) ; super . cancel ( true ) ; } } } </s>
|
<s> package de . ralfebert . imageassert ; import static org . junit . Assert . assertTrue ; import static org . junit . Assert . fail ; import org . junit . Before ; import org . junit . Test ; import de . ralfebert . imageassert . utils . Colocated ; public class ImageAssertTest { private ImageAssert imageAssert ; @ Before public void setup ( ) { imageAssert = new ImageAssert ( false ) ; } @ Test public void testEqualPages ( ) throws Exception { check ( "<STR_LIT>" , "<STR_LIT>" ) ; check ( "<STR_LIT>" , "<STR_LIT>" ) ; } @ Test ( expected = AssertionError . class ) public void testDifferentPage ( ) throws Exception { check ( "<STR_LIT>" , "<STR_LIT>" ) ; } @ Test ( expected = AssertionError . class ) public void testDifferentPages ( ) throws Exception { check ( "<STR_LIT>" , "<STR_LIT>" ) ; } @ Test ( expected = AssertionError . class ) public void testPagesSwapped ( ) throws Exception { check ( "<STR_LIT>" , "<STR_LIT>" ) ; } @ Test public void testNotEnoughPages ( ) throws Exception { try { check ( "<STR_LIT>" , "<STR_LIT>" ) ; fail ( "<STR_LIT>" ) ; } catch ( AssertionError e ) { assertTrue ( e . getMessage ( ) , e . getMessage ( ) . contains ( "<STR_LIT>" ) ) ; } } @ Test public void testTooManyPages ( ) throws Exception { try { check ( "<STR_LIT>" , "<STR_LIT>" ) ; fail ( "<STR_LIT>" ) ; } catch ( AssertionError e ) { assertTrue ( e . getMessage ( ) , e . getMessage ( ) . contains ( "<STR_LIT>" ) ) ; } } private void check ( String expected , String actual ) { imageAssert . assertPdfEquals ( Colocated . toStream ( this , expected ) , Colocated . toStream ( this , actual ) ) ; } } </s>
|
<s> package de . ralfebert . imageassert ; import static org . junit . Assert . assertEquals ; import java . io . File ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . util . Arrays ; import java . util . List ; import org . apache . commons . io . IOUtils ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; import org . junit . runner . RunWith ; import org . junit . runners . Parameterized ; import org . junit . runners . Parameterized . Parameters ; import de . ralfebert . imageassert . compare . Page ; import de . ralfebert . imageassert . pageimage . IPdfImageSplitter ; import de . ralfebert . imageassert . pageimage . ImageMagickSplitter ; import de . ralfebert . imageassert . pageimage . PdfRendererImageSplitter ; import de . ralfebert . imageassert . utils . Colocated ; import de . ralfebert . imageassert . utils . TemporaryFolder ; @ RunWith ( Parameterized . class ) public class PdfToPageImageConverterTest { private TemporaryFolder tempFolder ; private final IPdfImageSplitter converter ; public PdfToPageImageConverterTest ( IPdfImageSplitter converter ) { super ( ) ; this . converter = converter ; } @ Parameters public static List < Object [ ] > parameters ( ) { return Arrays . asList ( new Object [ ] [ ] { { new ImageMagickSplitter ( ) } , { new PdfRendererImageSplitter ( ) } } ) ; } @ Before public void setup ( ) { tempFolder = new TemporaryFolder ( this ) ; } @ After public void teardown ( ) { tempFolder . dispose ( ) ; } @ Test public void testConvert ( ) throws FileNotFoundException , IOException { converter . setTemporaryFolder ( tempFolder ) ; File file = tempFolder . createFile ( "<STR_LIT>" ) ; IOUtils . copy ( Colocated . toStream ( this , "<STR_LIT>" ) , new FileOutputStream ( file ) ) ; Page [ ] pages = converter . convert ( file ) ; assertEquals ( "<STR_LIT>" , <NUM_LIT:3> , pages . length ) ; } } </s>
|
<s> package de . ralfebert . imageassert . utils ; import static org . junit . Assert . * ; import org . junit . Before ; import org . junit . Test ; public class UnixLauncherTest { private UnixLauncher launcher ; @ Before public void setup ( ) { launcher = new UnixLauncher ( ) ; } @ Test public void testEcho ( ) throws Exception { assertEquals ( "<STR_LIT>" , launcher . launch ( "<STR_LIT>" , "<STR_LIT:x>" ) ) ; } @ Test public void testError ( ) throws Exception { try { launcher . launch ( "<STR_LIT>" , "<STR_LIT>" ) ; fail ( "<STR_LIT>" ) ; } catch ( LaunchException e ) { e . printStackTrace ( ) ; assertTrue ( e . getMessage ( ) , e . getMessage ( ) . contains ( "<STR_LIT>" ) ) ; assertTrue ( e . getMessage ( ) , e . getErrors ( ) . contains ( "<STR_LIT>" ) ) ; assertTrue ( e . getExitValue ( ) != <NUM_LIT:0> ) ; } } } </s>
|
<s> package de . ralfebert . imageassert . utils ; import static org . junit . Assert . assertEquals ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import org . apache . commons . io . IOUtils ; import org . junit . Test ; public class ColocatedTest { private static final String TEST = "<STR_LIT>" ; private static final String TEST_CONTENTS = "<STR_LIT:abc>" ; private static final String DOESNT_EXIST = "<STR_LIT>" ; @ Test public void testToString ( ) { assertEquals ( TEST_CONTENTS , Colocated . toString ( this , TEST ) ) ; } @ Test public void testToStream ( ) throws IOException { InputStream stream = Colocated . toStream ( this , TEST ) ; assertEquals ( TEST_CONTENTS , IOUtils . toString ( stream ) ) ; } @ Test public void testToURL ( ) throws IOException { URL url = Colocated . toURL ( this , TEST ) ; assertEquals ( TEST_CONTENTS , IOUtils . toString ( url . openStream ( ) ) ) ; } @ Test ( expected = RuntimeIOException . class ) public void testToStringError ( ) { Colocated . toString ( this , DOESNT_EXIST ) ; } @ Test ( expected = RuntimeIOException . class ) public void testToStreamError ( ) { Colocated . toStream ( this , DOESNT_EXIST ) ; } @ Test ( expected = RuntimeIOException . class ) public void testToURLError ( ) { Colocated . toURL ( this , DOESNT_EXIST ) ; } } </s>
|
<s> package de . ralfebert . imageassert . utils ; import static org . junit . Assert . * ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import org . apache . commons . io . IOUtils ; import org . junit . Test ; public class TemporaryFolderTest { @ Test public void testCreateFile ( ) throws Exception { TemporaryFolder folder = new TemporaryFolder ( this ) ; File file = folder . createFile ( "<STR_LIT>" ) ; assertNotNull ( file ) ; IOUtils . write ( "<STR_LIT:test>" , new FileOutputStream ( file ) ) ; assertTrue ( file . exists ( ) ) ; assertEquals ( "<STR_LIT:test>" , IOUtils . toString ( new FileInputStream ( file ) ) ) ; folder . dispose ( ) ; assertFalse ( file . exists ( ) ) ; } } </s>
|
<s> package de . ralfebert . imageassert . pageimage ; import java . io . File ; import java . io . FilenameFilter ; import java . util . Arrays ; import org . apache . commons . io . FilenameUtils ; import org . apache . commons . io . filefilter . WildcardFileFilter ; import de . ralfebert . imageassert . compare . Page ; import de . ralfebert . imageassert . utils . TemporaryFolder ; import de . ralfebert . imageassert . utils . UnixLauncher ; public class XpdfSplitter implements IPdfImageSplitter { private TemporaryFolder temporaryFolder ; private final UnixLauncher launcher = new UnixLauncher ( ) ; public void setTemporaryFolder ( TemporaryFolder temporaryFolder ) { this . temporaryFolder = temporaryFolder ; } public Page [ ] convert ( File pdf ) { String src = pdf . getAbsolutePath ( ) ; String dest = src . replaceAll ( "<STR_LIT>" , "<STR_LIT>" ) ; ProcessBuilder convertProcess = new ProcessBuilder ( "<STR_LIT>" , src , dest ) ; launcher . launch ( convertProcess ) ; String wildcard = FilenameUtils . getBaseName ( pdf . getAbsolutePath ( ) ) + "<STR_LIT>" ; File [ ] images = temporaryFolder . getFolder ( ) . listFiles ( ( FilenameFilter ) new WildcardFileFilter ( wildcard ) ) ; for ( int i = <NUM_LIT:0> ; i < images . length ; i ++ ) { String ppmPath = images [ i ] . getAbsolutePath ( ) ; String pngPath = ppmPath . replaceAll ( "<STR_LIT>" , "<STR_LIT>" ) ; convertProcess = new ProcessBuilder ( "<STR_LIT>" , ppmPath , "<STR_LIT>" , "<STR_LIT>" , pngPath ) ; launcher . launch ( convertProcess ) ; images [ i ] = new File ( pngPath ) ; } Arrays . sort ( images ) ; Page [ ] pages = new Page [ images . length ] ; for ( int i = <NUM_LIT:0> ; i < pages . length ; i ++ ) { pages [ i ] = new Page ( images [ i ] , pdf ) ; } return pages ; } } </s>
|
<s> package de . ralfebert . imageassert . pageimage ; import java . io . File ; import java . io . FilenameFilter ; import java . util . Arrays ; import org . apache . commons . io . FilenameUtils ; import org . apache . commons . io . filefilter . WildcardFileFilter ; import de . ralfebert . imageassert . compare . Page ; import de . ralfebert . imageassert . utils . TemporaryFolder ; import de . ralfebert . imageassert . utils . UnixLauncher ; public class ImageMagickSplitter implements IPdfImageSplitter { private final UnixLauncher launcher = new UnixLauncher ( ) ; private int dpi = <NUM_LIT> ; private TemporaryFolder temporaryFolder ; public Page [ ] convert ( File pdf ) { String src = pdf . getAbsolutePath ( ) ; String dest = src . replaceAll ( "<STR_LIT>" , "<STR_LIT>" ) ; ProcessBuilder convertProcess = new ProcessBuilder ( "<STR_LIT>" , "<STR_LIT>" , String . valueOf ( dpi ) , src , "<STR_LIT>" , "<STR_LIT>" , dest ) ; launcher . launch ( convertProcess ) ; String wildcard = FilenameUtils . getBaseName ( pdf . getAbsolutePath ( ) ) + "<STR_LIT>" ; File [ ] pngFiles = temporaryFolder . getFolder ( ) . listFiles ( ( FilenameFilter ) new WildcardFileFilter ( wildcard ) ) ; Arrays . sort ( pngFiles ) ; Page [ ] pages = new Page [ pngFiles . length ] ; for ( int i = <NUM_LIT:0> ; i < pages . length ; i ++ ) { pages [ i ] = new Page ( pngFiles [ i ] , pdf ) ; } return pages ; } public void setDpi ( int dpi ) { this . dpi = dpi ; } public void setTemporaryFolder ( TemporaryFolder temporaryFolder ) { this . temporaryFolder = temporaryFolder ; } } </s>
|
<s> package de . ralfebert . imageassert . pageimage ; import java . io . File ; import de . ralfebert . imageassert . compare . Page ; import de . ralfebert . imageassert . utils . TemporaryFolder ; public interface IPdfImageSplitter { public void setTemporaryFolder ( TemporaryFolder temporaryFolder ) ; public abstract Page [ ] convert ( File pdf ) ; } </s>
|
<s> package de . ralfebert . imageassert . pageimage ; import java . awt . Graphics2D ; import java . awt . Image ; import java . awt . Rectangle ; import java . awt . image . BufferedImage ; import java . io . File ; import java . io . IOException ; import java . io . RandomAccessFile ; import java . nio . ByteBuffer ; import java . nio . channels . FileChannel ; import com . sun . pdfview . PDFFile ; import com . sun . pdfview . PDFPage ; import de . ralfebert . imageassert . compare . Page ; import de . ralfebert . imageassert . utils . RuntimeIOException ; import de . ralfebert . imageassert . utils . TemporaryFolder ; public class PdfRendererImageSplitter implements IPdfImageSplitter { public Page [ ] convert ( File pdf ) { try { RandomAccessFile raf ; raf = new RandomAccessFile ( pdf , "<STR_LIT:r>" ) ; FileChannel channel = raf . getChannel ( ) ; ByteBuffer buffer = channel . map ( FileChannel . MapMode . READ_ONLY , <NUM_LIT:0> , channel . size ( ) ) ; PDFFile pdffile = new PDFFile ( buffer ) ; Page [ ] pages = new Page [ pdffile . getNumPages ( ) ] ; for ( int i = <NUM_LIT:0> ; i < pdffile . getNumPages ( ) ; i ++ ) { PDFPage page = pdffile . getPage ( i ) ; Rectangle rect = new Rectangle ( <NUM_LIT:0> , <NUM_LIT:0> , ( int ) page . getBBox ( ) . getWidth ( ) , ( int ) page . getBBox ( ) . getHeight ( ) ) ; Image img = page . getImage ( rect . width , rect . height , rect , null , true , true ) ; BufferedImage bufferedImage = new BufferedImage ( img . getWidth ( null ) , img . getHeight ( null ) , BufferedImage . TYPE_INT_RGB ) ; Graphics2D graphics2d = bufferedImage . createGraphics ( ) ; graphics2d . drawImage ( img , <NUM_LIT:0> , <NUM_LIT:0> , null ) ; pages [ i ] = new Page ( bufferedImage , pdf . getName ( ) , pdf ) ; } return pages ; } catch ( IOException e ) { throw new RuntimeIOException ( e ) ; } } public void setTemporaryFolder ( TemporaryFolder temporaryFolder ) { } } </s>
|
<s> package de . ralfebert . imageassert . compare ; import java . awt . image . BufferedImage ; import java . io . File ; import java . io . IOException ; import javax . imageio . ImageIO ; import de . ralfebert . imageassert . utils . RuntimeIOException ; public final class Page { private final String name ; private final BufferedImage image ; private final File pdfFile ; public Page ( File imageFile , File pdfFile ) { super ( ) ; this . name = imageFile . getName ( ) ; this . pdfFile = pdfFile ; try { image = ImageIO . read ( imageFile ) ; if ( image == null ) { throw new RuntimeException ( "<STR_LIT>" + imageFile ) ; } } catch ( IOException e ) { throw new RuntimeIOException ( e ) ; } } public Page ( BufferedImage image , String name , File pdfFile ) { this . image = image ; this . name = name ; this . pdfFile = pdfFile ; } public String getName ( ) { return name ; } public synchronized BufferedImage getImage ( ) { return image ; } public File getPdfFile ( ) { return pdfFile ; } } </s>
|
<s> package de . ralfebert . imageassert . compare ; public interface ICompareResultHandler { void onImageNotEqual ( Page expected , Page actual ) ; } </s>
|
<s> package de . ralfebert . imageassert . compare . junit ; import org . junit . Assert ; import de . ralfebert . imageassert . compare . ICompareResultHandler ; import de . ralfebert . imageassert . compare . Page ; public class JUnitCompareResultHandler implements ICompareResultHandler { public void onImageNotEqual ( Page expected , Page actual ) { Assert . fail ( String . format ( "<STR_LIT>" , expected . getName ( ) , actual . getName ( ) ) ) ; } } </s>
|
<s> package de . ralfebert . imageassert . compare . swing ; import static org . junit . Assert . fail ; import java . io . File ; import java . io . FileInputStream ; import java . io . FileOutputStream ; import java . util . logging . Logger ; import org . apache . commons . io . IOUtils ; import de . ralfebert . imageassert . compare . ICompareResultHandler ; import de . ralfebert . imageassert . compare . Page ; public class SwingCompareResultHandler implements ICompareResultHandler { private static final Logger log = Logger . getLogger ( SwingCompareResultHandler . class . getName ( ) ) ; public void onImageNotEqual ( final Page expected , final Page actual ) { ImageCompareDialog imageCompareDialog = new ImageCompareDialog ( expected . getImage ( ) , actual . getImage ( ) ) { @ Override protected void onApply ( File saveToFile ) { try { FileOutputStream out = new FileOutputStream ( saveToFile ) ; IOUtils . copy ( new FileInputStream ( actual . getPdfFile ( ) ) , out ) ; out . close ( ) ; log . info ( "<STR_LIT>" + saveToFile . getAbsolutePath ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } @ Override protected void onReject ( ) { fail ( "<STR_LIT>" + expected . getName ( ) ) ; } } ; imageCompareDialog . open ( ) ; } } </s>
|
<s> package de . ralfebert . imageassert . compare . swing ; import java . awt . BorderLayout ; import java . awt . Color ; import java . awt . Dimension ; import java . awt . Graphics ; import java . awt . GraphicsConfiguration ; import java . awt . GraphicsDevice ; import java . awt . GraphicsEnvironment ; import java . awt . Transparency ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . awt . event . KeyAdapter ; import java . awt . event . KeyEvent ; import java . awt . event . WindowAdapter ; import java . awt . event . WindowEvent ; import java . awt . image . BufferedImage ; import java . io . File ; import javax . swing . JButton ; import javax . swing . JComponent ; import javax . swing . JDialog ; import javax . swing . JFileChooser ; import javax . swing . JScrollPane ; public class ImageCompareDialog extends JDialog { private BufferedImage currentImage ; private boolean applied = false ; public ImageCompareDialog ( BufferedImage expected , BufferedImage actual ) { setTitle ( "<STR_LIT>" ) ; final BufferedImage expectedImage = makeCompatible ( expected ) ; final BufferedImage actualImage = makeCompatible ( actual ) ; this . currentImage = expectedImage ; final JComponent panel = new JComponent ( ) { @ Override public void paint ( Graphics g ) { g . drawImage ( currentImage , <NUM_LIT:0> , <NUM_LIT:0> , Color . WHITE , null ) ; } } ; panel . setPreferredSize ( new Dimension ( expectedImage . getWidth ( ) , expectedImage . getHeight ( ) ) ) ; JScrollPane scrollPane = new JScrollPane ( panel ) ; add ( scrollPane ) ; JButton applyButton = new JButton ( "<STR_LIT>" ) ; applyButton . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { JFileChooser fileChooser = new JFileChooser ( ) ; if ( fileChooser . showSaveDialog ( ImageCompareDialog . this ) == JFileChooser . APPROVE_OPTION ) { onApply ( fileChooser . getSelectedFile ( ) ) ; } applied = true ; setVisible ( false ) ; } } ) ; add ( applyButton , BorderLayout . PAGE_END ) ; addWindowListener ( new WindowAdapter ( ) { @ Override public void windowClosed ( WindowEvent e ) { if ( ! applied ) { onReject ( ) ; } } } ) ; setBackground ( Color . WHITE ) ; applyButton . addKeyListener ( new KeyAdapter ( ) { @ Override public void keyPressed ( KeyEvent e ) { if ( e . getKeyChar ( ) == '<CHAR_LIT:1>' ) { currentImage = expectedImage ; ImageCompareDialog . this . repaint ( ) ; } if ( e . getKeyChar ( ) == '<CHAR_LIT>' ) { currentImage = actualImage ; ImageCompareDialog . this . repaint ( ) ; } } } ) ; setSize ( expectedImage . getWidth ( ) + <NUM_LIT:30> , expectedImage . getHeight ( ) ) ; } private BufferedImage makeCompatible ( BufferedImage image ) { GraphicsEnvironment env = GraphicsEnvironment . getLocalGraphicsEnvironment ( ) ; GraphicsDevice device = env . getDefaultScreenDevice ( ) ; GraphicsConfiguration config = device . getDefaultConfiguration ( ) ; final BufferedImage compatibleImage = config . createCompatibleImage ( image . getWidth ( ) , image . getHeight ( ) , Transparency . TRANSLUCENT ) ; compatibleImage . getGraphics ( ) . drawImage ( image , <NUM_LIT:0> , <NUM_LIT:0> , null ) ; return compatibleImage ; } protected void onApply ( File file ) { } protected void onReject ( ) { } public void open ( ) { setModal ( true ) ; setVisible ( true ) ; } } </s>
|
<s> package de . ralfebert . imageassert . utils ; import java . io . IOException ; import java . io . InputStream ; import java . net . URL ; import org . apache . commons . io . IOUtils ; public class Colocated { public static String toString ( Object ownerObject , String filename ) { try { return IOUtils . toString ( toStream ( ownerObject , filename ) ) ; } catch ( IOException e ) { throw new RuntimeIOException ( e ) ; } } public static InputStream toStream ( Object ownerObject , String filename ) { Class < ? > ownerClass = ownerObject . getClass ( ) ; InputStream stream = ownerObject . getClass ( ) . getResourceAsStream ( filename ) ; if ( stream == null ) { throw new RuntimeIOException ( String . format ( "<STR_LIT>" , filename , ownerClass . getPackage ( ) ) ) ; } return stream ; } public static URL toURL ( Object ownerObject , String filename ) { Class < ? > ownerClass = ownerObject . getClass ( ) ; URL url = ownerObject . getClass ( ) . getResource ( filename ) ; if ( url == null ) { throw new RuntimeIOException ( String . format ( "<STR_LIT>" , filename , ownerClass . getPackage ( ) ) ) ; } return url ; } } </s>
|
<s> package de . ralfebert . imageassert . utils ; import java . io . IOException ; public class RuntimeIOException extends RuntimeException { private static final long serialVersionUID = <NUM_LIT:1L> ; public RuntimeIOException ( String message ) { super ( message ) ; } public RuntimeIOException ( IOException cause ) { super ( cause ) ; } } </s>
|
<s> package de . ralfebert . imageassert . utils ; import java . io . File ; import java . io . IOException ; import java . util . logging . Logger ; import org . apache . commons . io . FileUtils ; public class TemporaryFolder { private final static Logger log = Logger . getLogger ( "<STR_LIT>" ) ; private final String name ; private File folder ; public TemporaryFolder ( String name ) { this . name = name ; } public TemporaryFolder ( Object forObject ) { this . name = forObject . getClass ( ) . getSimpleName ( ) ; } public File createFile ( String filename ) { return new File ( getFolder ( ) , filename ) ; } public File getFolder ( ) { if ( folder == null ) { try { folder = File . createTempFile ( name , "<STR_LIT>" ) ; } catch ( IOException e ) { throw new RuntimeIOException ( e ) ; } if ( folder . exists ( ) ) { folder . delete ( ) ; } if ( ! this . folder . mkdirs ( ) ) { throw new RuntimeIOException ( String . format ( "<STR_LIT>" , folder ) ) ; } log . info ( "<STR_LIT>" + folder ) ; } return folder ; } public void dispose ( ) { if ( this . folder != null ) { try { FileUtils . deleteDirectory ( this . folder ) ; } catch ( IOException e ) { throw new RuntimeIOException ( e ) ; } log . info ( "<STR_LIT>" + folder ) ; } } } </s>
|
<s> package de . ralfebert . imageassert . utils ; import org . apache . commons . lang . StringUtils ; public class LaunchException extends RuntimeException { private static final long serialVersionUID = <NUM_LIT:1L> ; private final int exitValue ; private final String commandLine ; private final String output ; private final String errors ; public LaunchException ( int exitValue , String commandLine , String output , String errors ) { this . exitValue = exitValue ; this . commandLine = commandLine ; this . output = output ; this . errors = errors ; } @ Override public String getMessage ( ) { String message = String . format ( "<STR_LIT>" , exitValue , commandLine ) ; if ( StringUtils . isNotBlank ( errors ) ) { message += "<STR_LIT>" + errors . trim ( ) ; } if ( StringUtils . isNotBlank ( output ) ) { message += "<STR_LIT>" + output . trim ( ) ; } return message ; } public String getCommandLine ( ) { return commandLine ; } public String getErrors ( ) { return errors ; } public String getOutput ( ) { return output ; } public int getExitValue ( ) { return exitValue ; } } </s>
|
<s> package de . ralfebert . imageassert . utils ; import java . io . IOException ; import java . util . logging . Logger ; import org . apache . commons . io . IOUtils ; import org . apache . commons . lang . StringUtils ; public class UnixLauncher { private final static Logger log = Logger . getLogger ( "<STR_LIT>" ) ; public static final int EXIT_SUCCESS = <NUM_LIT:0> ; public static final int EXIT_FAILURE = <NUM_LIT:1> ; public String launch ( ProcessBuilder processBuilder ) throws LaunchException { try { String commandLine = StringUtils . join ( processBuilder . command ( ) . iterator ( ) , "<STR_LIT:U+0020>" ) ; log . info ( "<STR_LIT>" + commandLine ) ; Process process = processBuilder . start ( ) ; int exitValue = process . waitFor ( ) ; String output = IOUtils . toString ( process . getInputStream ( ) ) ; if ( exitValue == EXIT_SUCCESS ) { return output ; } else { throw new LaunchException ( exitValue , commandLine , IOUtils . toString ( process . getInputStream ( ) ) , IOUtils . toString ( process . getErrorStream ( ) ) ) ; } } catch ( IOException e ) { throw new RuntimeIOException ( e ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } public String launch ( String ... command ) throws LaunchException { return launch ( new ProcessBuilder ( command ) ) ; } } </s>
|
<s> package de . ralfebert . imageassert ; import static org . junit . Assert . fail ; import java . awt . GraphicsEnvironment ; import java . awt . image . BufferedImage ; import java . io . File ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . Arrays ; import org . apache . commons . io . IOUtils ; import de . ralfebert . imageassert . compare . ICompareResultHandler ; import de . ralfebert . imageassert . compare . Page ; import de . ralfebert . imageassert . compare . junit . JUnitCompareResultHandler ; import de . ralfebert . imageassert . compare . swing . SwingCompareResultHandler ; import de . ralfebert . imageassert . pageimage . IPdfImageSplitter ; import de . ralfebert . imageassert . pageimage . PdfRendererImageSplitter ; import de . ralfebert . imageassert . utils . RuntimeIOException ; import de . ralfebert . imageassert . utils . TemporaryFolder ; public class ImageAssert { private ICompareResultHandler compareResultHandler = new JUnitCompareResultHandler ( ) ; private IPdfImageSplitter pdfImageSplitter = new PdfRendererImageSplitter ( ) ; public ImageAssert ( ) { this ( ! GraphicsEnvironment . isHeadless ( ) ) ; } public ImageAssert ( boolean showCompareDialog ) { if ( showCompareDialog ) { setCompareResultHandler ( new SwingCompareResultHandler ( ) ) ; } } private void assertImageEquals ( Page expectedImage , Page actualImage ) { boolean equal = Arrays . equals ( extractPixels ( expectedImage . getImage ( ) ) , extractPixels ( actualImage . getImage ( ) ) ) ; if ( ! equal ) { compareResultHandler . onImageNotEqual ( expectedImage , actualImage ) ; } } private int [ ] extractPixels ( BufferedImage image ) { return image . getRaster ( ) . getPixels ( <NUM_LIT:0> , <NUM_LIT:0> , image . getWidth ( ) , image . getHeight ( ) , ( int [ ] ) null ) ; } public void assertPdfEquals ( InputStream expected , InputStream actual ) { TemporaryFolder temporaryFolder = new TemporaryFolder ( this ) ; try { Page [ ] expectedPages = extractPages ( expected , "<STR_LIT>" , temporaryFolder ) ; Page [ ] actualPages = extractPages ( actual , "<STR_LIT>" , temporaryFolder ) ; if ( expectedPages . length <= <NUM_LIT:0> ) fail ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < expectedPages . length ; i ++ ) { Page expectedPage = expectedPages [ i ] ; if ( i >= actualPages . length ) { fail ( String . format ( "<STR_LIT>" , actualPages . length , expectedPages . length ) ) ; } Page actualPage = actualPages [ i ] ; assertImageEquals ( expectedPage , actualPage ) ; } if ( actualPages . length != expectedPages . length ) { fail ( String . format ( "<STR_LIT>" , actualPages . length , expectedPages . length ) ) ; } } finally { temporaryFolder . dispose ( ) ; } } private Page [ ] extractPages ( InputStream pdfStream , String pdfName , TemporaryFolder temp ) { pdfImageSplitter . setTemporaryFolder ( temp ) ; File actualFile = temp . createFile ( pdfName ) ; FileOutputStream output = null ; try { output = new FileOutputStream ( actualFile ) ; IOUtils . copy ( pdfStream , output ) ; } catch ( IOException e ) { throw new RuntimeIOException ( e ) ; } finally { IOUtils . closeQuietly ( output ) ; } return pdfImageSplitter . convert ( actualFile ) ; } public void setCompareResultHandler ( ICompareResultHandler compareResultHandler ) { this . compareResultHandler = compareResultHandler ; } public void setPdfImageSplitter ( IPdfImageSplitter pdfImageSplitter ) { this . pdfImageSplitter = pdfImageSplitter ; } } </s>
|
<s> package org . apache . gora . cassandra . query ; import java . nio . ByteBuffer ; import me . prettyprint . hector . api . Serializer ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Field ; import org . apache . avro . Schema . Type ; import org . apache . gora . cassandra . serializers . GoraSerializerTypeInferer ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public abstract class CassandraColumn { public static final Logger LOG = LoggerFactory . getLogger ( CassandraColumn . class ) ; public static final int SUB = <NUM_LIT:0> ; public static final int SUPER = <NUM_LIT:1> ; private String family ; private int type ; private Field field ; public String getFamily ( ) { return family ; } public void setFamily ( String family ) { this . family = family ; } public int getType ( ) { return type ; } public void setType ( int type ) { this . type = type ; } public void setField ( Field field ) { this . field = field ; } protected Field getField ( ) { return this . field ; } public abstract ByteBuffer getName ( ) ; public abstract Object getValue ( ) ; protected Object fromByteBuffer ( Schema schema , ByteBuffer byteBuffer ) { Object value = null ; Serializer serializer = GoraSerializerTypeInferer . getSerializer ( schema ) ; if ( serializer == null ) { LOG . info ( "<STR_LIT>" + schema . toString ( ) ) ; } else { value = serializer . fromByteBuffer ( byteBuffer ) ; } return value ; } } </s>
|
<s> package org . apache . gora . cassandra . query ; import java . io . IOException ; import java . util . List ; import java . util . Map ; import me . prettyprint . cassandra . serializers . StringSerializer ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Field ; import org . apache . avro . specific . SpecificFixed ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . query . Query ; import org . apache . gora . query . impl . ResultBase ; import org . apache . gora . store . DataStore ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CassandraResult < K , T extends Persistent > extends ResultBase < K , T > { public static final Logger LOG = LoggerFactory . getLogger ( CassandraResult . class ) ; private int rowNumber ; private CassandraResultSet < K > cassandraResultSet ; private Map < String , String > reverseMap ; public CassandraResult ( DataStore < K , T > dataStore , Query < K , T > query ) { super ( dataStore , query ) ; } @ Override protected boolean nextInner ( ) throws IOException { if ( this . rowNumber < this . cassandraResultSet . size ( ) ) { updatePersistent ( ) ; } ++ this . rowNumber ; return ( this . rowNumber <= this . cassandraResultSet . size ( ) ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) private void updatePersistent ( ) throws IOException { CassandraRow < K > cassandraRow = this . cassandraResultSet . get ( this . rowNumber ) ; this . key = cassandraRow . getKey ( ) ; Schema schema = this . persistent . getSchema ( ) ; List < Field > fields = schema . getFields ( ) ; for ( CassandraColumn cassandraColumn : cassandraRow ) { String family = cassandraColumn . getFamily ( ) ; String fieldName = this . reverseMap . get ( family + "<STR_LIT::>" + StringSerializer . get ( ) . fromByteBuffer ( cassandraColumn . getName ( ) ) ) ; int pos = this . persistent . getFieldIndex ( fieldName ) ; Field field = fields . get ( pos ) ; cassandraColumn . setField ( field ) ; Object value = cassandraColumn . getValue ( ) ; this . persistent . put ( pos , value ) ; this . persistent . clearDirty ( pos ) ; } } @ Override public void close ( ) throws IOException { } @ Override public float getProgress ( ) throws IOException { return ( ( ( float ) this . rowNumber ) / this . cassandraResultSet . size ( ) ) ; } public void setResultSet ( CassandraResultSet < K > cassandraResultSet ) { this . cassandraResultSet = cassandraResultSet ; } public void setReverseMap ( Map < String , String > reverseMap ) { this . reverseMap = reverseMap ; } } </s>
|
<s> package org . apache . gora . cassandra . query ; import java . util . List ; import java . util . Map ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . query . Query ; import org . apache . gora . query . impl . QueryBase ; import org . apache . gora . store . DataStore ; public class CassandraQuery < K , T extends Persistent > extends QueryBase < K , T > { private Query < K , T > query ; private Map < String , List < String > > familyMap ; public CassandraQuery ( ) { super ( null ) ; } public CassandraQuery ( DataStore < K , T > dataStore ) { super ( dataStore ) ; } public void setFamilyMap ( Map < String , List < String > > familyMap ) { this . familyMap = familyMap ; } public Map < String , List < String > > getFamilyMap ( ) { return familyMap ; } public String [ ] getColumns ( String family ) { List < String > columnList = familyMap . get ( family ) ; String [ ] columns = new String [ columnList . size ( ) ] ; for ( int i = <NUM_LIT:0> ; i < columns . length ; ++ i ) { columns [ i ] = columnList . get ( i ) ; } return columns ; } public Query < K , T > getQuery ( ) { return query ; } public void setQuery ( Query < K , T > query ) { this . query = query ; } } </s>
|
<s> package org . apache . gora . cassandra . query ; import java . nio . ByteBuffer ; import java . nio . CharBuffer ; import java . nio . charset . CharacterCodingException ; import java . nio . charset . Charset ; import java . nio . charset . CharsetEncoder ; import me . prettyprint . cassandra . serializers . FloatSerializer ; import me . prettyprint . cassandra . serializers . DoubleSerializer ; import me . prettyprint . cassandra . serializers . IntegerSerializer ; import me . prettyprint . cassandra . serializers . LongSerializer ; import me . prettyprint . cassandra . serializers . StringSerializer ; import me . prettyprint . hector . api . beans . HColumn ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Field ; import org . apache . avro . Schema . Type ; import org . apache . avro . generic . GenericArray ; import org . apache . avro . generic . GenericData ; import org . apache . avro . util . Utf8 ; import org . apache . gora . cassandra . serializers . GenericArraySerializer ; import org . apache . gora . cassandra . serializers . StatefulHashMapSerializer ; import org . apache . gora . cassandra . serializers . TypeUtils ; import org . apache . gora . persistency . StatefulHashMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CassandraSubColumn extends CassandraColumn { public static final Logger LOG = LoggerFactory . getLogger ( CassandraSubColumn . class ) ; private static final String ENCODING = "<STR_LIT:UTF-8>" ; private static CharsetEncoder charsetEncoder = Charset . forName ( ENCODING ) . newEncoder ( ) ; ; private HColumn < ByteBuffer , ByteBuffer > hColumn ; public ByteBuffer getName ( ) { return hColumn . getName ( ) ; } public Object getValue ( ) { Field field = getField ( ) ; Schema fieldSchema = field . schema ( ) ; Type type = fieldSchema . getType ( ) ; ByteBuffer byteBuffer = hColumn . getValue ( ) ; if ( byteBuffer == null ) { return null ; } Object value = null ; if ( type == Type . ARRAY ) { GenericArraySerializer serializer = GenericArraySerializer . get ( fieldSchema . getElementType ( ) ) ; GenericArray genericArray = serializer . fromByteBuffer ( byteBuffer ) ; value = genericArray ; } else if ( type == Type . MAP ) { StatefulHashMapSerializer serializer = StatefulHashMapSerializer . get ( fieldSchema . getValueType ( ) ) ; StatefulHashMap map = serializer . fromByteBuffer ( byteBuffer ) ; value = map ; } else { value = fromByteBuffer ( fieldSchema , byteBuffer ) ; } return value ; } public void setValue ( HColumn < ByteBuffer , ByteBuffer > hColumn ) { this . hColumn = hColumn ; } } </s>
|
<s> package org . apache . gora . cassandra . query ; import java . util . ArrayList ; public class CassandraRow < K > extends ArrayList < CassandraColumn > { private static final long serialVersionUID = - <NUM_LIT> ; private K key ; public K getKey ( ) { return this . key ; } public void setKey ( K key ) { this . key = key ; } } </s>
|
<s> package org . apache . gora . cassandra . query ; import java . util . ArrayList ; import java . util . HashMap ; public class CassandraResultSet < K > extends ArrayList < CassandraRow < K > > { private static final long serialVersionUID = - <NUM_LIT> ; private HashMap < K , Integer > indexMap = new HashMap < K , Integer > ( ) ; public CassandraRow < K > getRow ( K key ) { Integer integer = this . indexMap . get ( key ) ; if ( integer == null ) { return null ; } return this . get ( integer ) ; } public void putRow ( K key , CassandraRow < K > cassandraRow ) { this . add ( cassandraRow ) ; this . indexMap . put ( key , this . size ( ) - <NUM_LIT:1> ) ; } } </s>
|
<s> package org . apache . gora . cassandra . query ; import java . nio . ByteBuffer ; import java . util . Map ; import me . prettyprint . cassandra . serializers . IntegerSerializer ; import me . prettyprint . cassandra . serializers . StringSerializer ; import me . prettyprint . hector . api . beans . HColumn ; import me . prettyprint . hector . api . beans . HSuperColumn ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Field ; import org . apache . avro . Schema . Type ; import org . apache . avro . generic . GenericArray ; import org . apache . avro . util . Utf8 ; import org . apache . gora . cassandra . serializers . Utf8Serializer ; import org . apache . gora . persistency . ListGenericArray ; import org . apache . gora . persistency . StatefulHashMap ; import org . apache . gora . persistency . impl . PersistentBase ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CassandraSuperColumn extends CassandraColumn { public static final Logger LOG = LoggerFactory . getLogger ( CassandraSuperColumn . class ) ; private HSuperColumn < String , ByteBuffer , ByteBuffer > hSuperColumn ; public ByteBuffer getName ( ) { return StringSerializer . get ( ) . toByteBuffer ( hSuperColumn . getName ( ) ) ; } public Object getValue ( ) { Field field = getField ( ) ; Schema fieldSchema = field . schema ( ) ; Type type = fieldSchema . getType ( ) ; Object value = null ; switch ( type ) { case ARRAY : ListGenericArray array = new ListGenericArray ( fieldSchema . getElementType ( ) ) ; for ( HColumn < ByteBuffer , ByteBuffer > hColumn : this . hSuperColumn . getColumns ( ) ) { ByteBuffer memberByteBuffer = hColumn . getValue ( ) ; Object memberValue = fromByteBuffer ( fieldSchema . getElementType ( ) , hColumn . getValue ( ) ) ; array . add ( memberValue ) ; } value = array ; break ; case MAP : Map < Utf8 , Object > map = new StatefulHashMap < Utf8 , Object > ( ) ; for ( HColumn < ByteBuffer , ByteBuffer > hColumn : this . hSuperColumn . getColumns ( ) ) { ByteBuffer memberByteBuffer = hColumn . getValue ( ) ; Object memberValue = null ; memberValue = fromByteBuffer ( fieldSchema . getValueType ( ) , hColumn . getValue ( ) ) ; map . put ( Utf8Serializer . get ( ) . fromByteBuffer ( hColumn . getName ( ) ) , memberValue ) ; } value = map ; break ; case RECORD : String fullName = fieldSchema . getFullName ( ) ; Class < ? > claz = null ; try { claz = Class . forName ( fullName ) ; } catch ( ClassNotFoundException cnfe ) { LOG . warn ( "<STR_LIT>" + fullName , cnfe ) ; break ; } try { value = claz . newInstance ( ) ; } catch ( InstantiationException ie ) { LOG . warn ( "<STR_LIT>" , ie ) ; break ; } catch ( IllegalAccessException iae ) { LOG . warn ( "<STR_LIT>" , iae ) ; break ; } if ( value instanceof PersistentBase ) { PersistentBase record = ( PersistentBase ) value ; for ( HColumn < ByteBuffer , ByteBuffer > hColumn : this . hSuperColumn . getColumns ( ) ) { String memberName = StringSerializer . get ( ) . fromByteBuffer ( hColumn . getName ( ) ) ; if ( memberName == null || memberName . length ( ) == <NUM_LIT:0> ) { LOG . warn ( "<STR_LIT>" ) ; continue ; } Field memberField = fieldSchema . getField ( memberName ) ; CassandraSubColumn cassandraColumn = new CassandraSubColumn ( ) ; cassandraColumn . setField ( memberField ) ; cassandraColumn . setValue ( hColumn ) ; record . put ( record . getFieldIndex ( memberName ) , cassandraColumn . getValue ( ) ) ; } } break ; default : LOG . info ( "<STR_LIT>" + type ) ; } return value ; } public void setValue ( HSuperColumn < String , ByteBuffer , ByteBuffer > hSuperColumn ) { this . hSuperColumn = hSuperColumn ; } } </s>
|
<s> package org . apache . gora . cassandra . store ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import me . prettyprint . cassandra . model . BasicColumnFamilyDefinition ; import me . prettyprint . cassandra . service . ThriftCfDef ; import me . prettyprint . hector . api . ddl . ColumnFamilyDefinition ; import me . prettyprint . hector . api . ddl . ColumnType ; import me . prettyprint . hector . api . ddl . ComparatorType ; import org . jdom . Document ; import org . jdom . Element ; import org . jdom . JDOMException ; import org . jdom . input . SAXBuilder ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CassandraMapping { public static final Logger LOG = LoggerFactory . getLogger ( CassandraMapping . class ) ; private static final String MAPPING_FILE = "<STR_LIT>" ; private static final String KEYSPACE_ELEMENT = "<STR_LIT>" ; private static final String NAME_ATTRIBUTE = "<STR_LIT:name>" ; private static final String MAPPING_ELEMENT = "<STR_LIT:class>" ; private static final String COLUMN_ATTRIBUTE = "<STR_LIT>" ; private static final String FAMILY_ATTRIBUTE = "<STR_LIT>" ; private static final String SUPER_ATTRIBUTE = "<STR_LIT:type>" ; private static final String CLUSTER_ATTRIBUTE = "<STR_LIT>" ; private static final String HOST_ATTRIBUTE = "<STR_LIT>" ; private String hostName ; private String clusterName ; private String keyspaceName ; private List < String > superFamilies = new ArrayList < String > ( ) ; private Map < String , String > familyMap = new HashMap < String , String > ( ) ; private Map < String , String > columnMap = new HashMap < String , String > ( ) ; private Map < String , BasicColumnFamilyDefinition > columnFamilyDefinitions = new HashMap < String , BasicColumnFamilyDefinition > ( ) ; public String getHostName ( ) { return this . hostName ; } public String getClusterName ( ) { return this . clusterName ; } public String getKeyspaceName ( ) { return this . keyspaceName ; } public CassandraMapping ( Element keyspace , Element mapping ) { if ( keyspace == null ) { LOG . warn ( "<STR_LIT>" ) ; } else { } this . keyspaceName = keyspace . getAttributeValue ( NAME_ATTRIBUTE ) ; if ( this . keyspaceName == null ) { LOG . warn ( "<STR_LIT>" ) ; } else { } this . clusterName = keyspace . getAttributeValue ( CLUSTER_ATTRIBUTE ) ; if ( this . clusterName == null ) { LOG . warn ( "<STR_LIT>" ) ; } else { } this . hostName = keyspace . getAttributeValue ( HOST_ATTRIBUTE ) ; if ( this . hostName == null ) { LOG . warn ( "<STR_LIT>" ) ; } else { } List < Element > elements = keyspace . getChildren ( ) ; for ( Element element : elements ) { BasicColumnFamilyDefinition cfDef = new BasicColumnFamilyDefinition ( ) ; String familyName = element . getAttributeValue ( NAME_ATTRIBUTE ) ; if ( familyName == null ) { LOG . warn ( "<STR_LIT>" ) ; } else { } String superAttribute = element . getAttributeValue ( SUPER_ATTRIBUTE ) ; if ( superAttribute != null ) { this . superFamilies . add ( familyName ) ; cfDef . setColumnType ( ColumnType . SUPER ) ; cfDef . setSubComparatorType ( ComparatorType . BYTESTYPE ) ; } cfDef . setKeyspaceName ( this . keyspaceName ) ; cfDef . setName ( familyName ) ; cfDef . setComparatorType ( ComparatorType . BYTESTYPE ) ; cfDef . setDefaultValidationClass ( ComparatorType . BYTESTYPE . getClassName ( ) ) ; this . columnFamilyDefinitions . put ( familyName , cfDef ) ; } elements = mapping . getChildren ( ) ; for ( Element element : elements ) { String fieldName = element . getAttributeValue ( NAME_ATTRIBUTE ) ; String familyName = element . getAttributeValue ( FAMILY_ATTRIBUTE ) ; String columnName = element . getAttributeValue ( COLUMN_ATTRIBUTE ) ; BasicColumnFamilyDefinition columnFamilyDefinition = this . columnFamilyDefinitions . get ( familyName ) ; if ( columnFamilyDefinition == null ) { LOG . warn ( "<STR_LIT>" + familyName + "<STR_LIT>" ) ; } this . familyMap . put ( fieldName , familyName ) ; this . columnMap . put ( fieldName , columnName ) ; } } public String getFamily ( String name ) { return this . familyMap . get ( name ) ; } public String getColumn ( String name ) { return this . columnMap . get ( name ) ; } public boolean isSuper ( String family ) { return this . superFamilies . indexOf ( family ) != - <NUM_LIT:1> ; } public List < ColumnFamilyDefinition > getColumnFamilyDefinitions ( ) { List < ColumnFamilyDefinition > list = new ArrayList < ColumnFamilyDefinition > ( ) ; for ( String key : this . columnFamilyDefinitions . keySet ( ) ) { ColumnFamilyDefinition columnFamilyDefinition = this . columnFamilyDefinitions . get ( key ) ; ThriftCfDef thriftCfDef = new ThriftCfDef ( columnFamilyDefinition ) ; list . add ( thriftCfDef ) ; } return list ; } } </s>
|
<s> package org . apache . gora . cassandra . store ; import java . io . IOException ; import java . nio . ByteBuffer ; import java . util . ArrayList ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Set ; import me . prettyprint . cassandra . serializers . IntegerSerializer ; import me . prettyprint . cassandra . serializers . StringSerializer ; import me . prettyprint . hector . api . beans . ColumnSlice ; import me . prettyprint . hector . api . beans . HColumn ; import me . prettyprint . hector . api . beans . HSuperColumn ; import me . prettyprint . hector . api . beans . Row ; import me . prettyprint . hector . api . beans . SuperRow ; import me . prettyprint . hector . api . beans . SuperSlice ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Field ; import org . apache . avro . Schema . Type ; import org . apache . avro . generic . GenericArray ; import org . apache . avro . specific . SpecificFixed ; import org . apache . avro . util . Utf8 ; import org . apache . gora . cassandra . query . CassandraQuery ; import org . apache . gora . cassandra . query . CassandraResult ; import org . apache . gora . cassandra . query . CassandraResultSet ; import org . apache . gora . cassandra . query . CassandraRow ; import org . apache . gora . cassandra . query . CassandraSubColumn ; import org . apache . gora . cassandra . query . CassandraSuperColumn ; import org . apache . gora . persistency . ListGenericArray ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . persistency . StatefulHashMap ; import org . apache . gora . persistency . impl . PersistentBase ; import org . apache . gora . persistency . impl . StateManagerImpl ; import org . apache . gora . query . PartitionQuery ; import org . apache . gora . query . Query ; import org . apache . gora . query . Result ; import org . apache . gora . query . impl . PartitionQueryImpl ; import org . apache . gora . store . impl . DataStoreBase ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CassandraStore < K , T extends Persistent > extends DataStoreBase < K , T > { public static final Logger LOG = LoggerFactory . getLogger ( CassandraStore . class ) ; private CassandraClient < K , T > cassandraClient = new CassandraClient < K , T > ( ) ; private Map < K , T > buffer = new LinkedHashMap < K , T > ( ) ; public CassandraStore ( ) throws Exception { } public void initialize ( Class < K > keyClass , Class < T > persistent , Properties properties ) throws IOException { super . initialize ( keyClass , persistent , properties ) ; try { this . cassandraClient . initialize ( keyClass , persistent ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) , e ) ; } } @ Override public void close ( ) throws IOException { LOG . debug ( "<STR_LIT>" ) ; flush ( ) ; } @ Override public void createSchema ( ) { LOG . debug ( "<STR_LIT>" ) ; this . cassandraClient . checkKeyspace ( ) ; } @ Override public boolean delete ( K key ) throws IOException { LOG . debug ( "<STR_LIT>" + key ) ; return false ; } @ Override public long deleteByQuery ( Query < K , T > query ) throws IOException { LOG . debug ( "<STR_LIT>" + query ) ; return <NUM_LIT:0> ; } @ Override public void deleteSchema ( ) throws IOException { LOG . debug ( "<STR_LIT>" ) ; this . cassandraClient . dropKeyspace ( ) ; } @ Override public Result < K , T > execute ( Query < K , T > query ) throws IOException { Map < String , List < String > > familyMap = this . cassandraClient . getFamilyMap ( query ) ; Map < String , String > reverseMap = this . cassandraClient . getReverseMap ( query ) ; CassandraQuery < K , T > cassandraQuery = new CassandraQuery < K , T > ( ) ; cassandraQuery . setQuery ( query ) ; cassandraQuery . setFamilyMap ( familyMap ) ; CassandraResult < K , T > cassandraResult = new CassandraResult < K , T > ( this , query ) ; cassandraResult . setReverseMap ( reverseMap ) ; CassandraResultSet cassandraResultSet = new CassandraResultSet ( ) ; for ( String family : familyMap . keySet ( ) ) { if ( family == null ) { continue ; } if ( this . cassandraClient . isSuper ( family ) ) { addSuperColumns ( family , cassandraQuery , cassandraResultSet ) ; } else { addSubColumns ( family , cassandraQuery , cassandraResultSet ) ; } } cassandraResult . setResultSet ( cassandraResultSet ) ; return cassandraResult ; } private void addSubColumns ( String family , CassandraQuery < K , T > cassandraQuery , CassandraResultSet cassandraResultSet ) { List < Row < K , ByteBuffer , ByteBuffer > > rows = this . cassandraClient . execute ( cassandraQuery , family ) ; for ( Row < K , ByteBuffer , ByteBuffer > row : rows ) { K key = row . getKey ( ) ; CassandraRow < K > cassandraRow = cassandraResultSet . getRow ( key ) ; if ( cassandraRow == null ) { cassandraRow = new CassandraRow < K > ( ) ; cassandraResultSet . putRow ( key , cassandraRow ) ; cassandraRow . setKey ( key ) ; } ColumnSlice < ByteBuffer , ByteBuffer > columnSlice = row . getColumnSlice ( ) ; for ( HColumn < ByteBuffer , ByteBuffer > hColumn : columnSlice . getColumns ( ) ) { CassandraSubColumn cassandraSubColumn = new CassandraSubColumn ( ) ; cassandraSubColumn . setValue ( hColumn ) ; cassandraSubColumn . setFamily ( family ) ; cassandraRow . add ( cassandraSubColumn ) ; } } } private void addSuperColumns ( String family , CassandraQuery < K , T > cassandraQuery , CassandraResultSet cassandraResultSet ) { List < SuperRow < K , String , ByteBuffer , ByteBuffer > > superRows = this . cassandraClient . executeSuper ( cassandraQuery , family ) ; for ( SuperRow < K , String , ByteBuffer , ByteBuffer > superRow : superRows ) { K key = superRow . getKey ( ) ; CassandraRow < K > cassandraRow = cassandraResultSet . getRow ( key ) ; if ( cassandraRow == null ) { cassandraRow = new CassandraRow ( ) ; cassandraResultSet . putRow ( key , cassandraRow ) ; cassandraRow . setKey ( key ) ; } SuperSlice < String , ByteBuffer , ByteBuffer > superSlice = superRow . getSuperSlice ( ) ; for ( HSuperColumn < String , ByteBuffer , ByteBuffer > hSuperColumn : superSlice . getSuperColumns ( ) ) { CassandraSuperColumn cassandraSuperColumn = new CassandraSuperColumn ( ) ; cassandraSuperColumn . setValue ( hSuperColumn ) ; cassandraSuperColumn . setFamily ( family ) ; cassandraRow . add ( cassandraSuperColumn ) ; } } } @ Override public void flush ( ) throws IOException { Set < K > keys = this . buffer . keySet ( ) ; K [ ] keyArray = ( K [ ] ) keys . toArray ( ) ; for ( K key : keyArray ) { T value = this . buffer . get ( key ) ; if ( value == null ) { LOG . info ( "<STR_LIT>" + key ) ; continue ; } Schema schema = value . getSchema ( ) ; for ( Field field : schema . getFields ( ) ) { if ( value . isDirty ( field . pos ( ) ) ) { addOrUpdateField ( key , field , value . get ( field . pos ( ) ) ) ; } } } for ( K key : keyArray ) { this . buffer . remove ( key ) ; } } @ Override public T get ( K key , String [ ] fields ) throws IOException { CassandraQuery < K , T > query = new CassandraQuery < K , T > ( ) ; query . setDataStore ( this ) ; query . setKeyRange ( key , key ) ; query . setFields ( fields ) ; query . setLimit ( <NUM_LIT:1> ) ; Result < K , T > result = execute ( query ) ; boolean hasResult = result . next ( ) ; return hasResult ? result . get ( ) : null ; } @ Override public List < PartitionQuery < K , T > > getPartitions ( Query < K , T > query ) throws IOException { List < PartitionQuery < K , T > > partitions = new ArrayList < PartitionQuery < K , T > > ( ) ; partitions . add ( new PartitionQueryImpl < K , T > ( query ) ) ; return partitions ; } @ Override public String getSchemaName ( ) { return this . cassandraClient . getKeyspaceName ( ) ; } @ Override public Query < K , T > newQuery ( ) { Query < K , T > query = new CassandraQuery < K , T > ( this ) ; query . setFields ( getFieldsToQuery ( null ) ) ; return query ; } @ Override public void put ( K key , T value ) throws IOException { T p = ( T ) value . newInstance ( new StateManagerImpl ( ) ) ; Schema schema = value . getSchema ( ) ; for ( Field field : schema . getFields ( ) ) { int fieldPos = field . pos ( ) ; if ( value . isDirty ( fieldPos ) ) { Object fieldValue = value . get ( fieldPos ) ; Schema fieldSchema = field . schema ( ) ; Type type = fieldSchema . getType ( ) ; switch ( type ) { case RECORD : Persistent persistent = ( Persistent ) fieldValue ; Persistent newRecord = persistent . newInstance ( new StateManagerImpl ( ) ) ; for ( Field member : fieldSchema . getFields ( ) ) { newRecord . put ( member . pos ( ) , persistent . get ( member . pos ( ) ) ) ; } fieldValue = newRecord ; break ; case MAP : break ; case ARRAY : GenericArray array = ( GenericArray ) fieldValue ; ListGenericArray newArray = new ListGenericArray ( fieldSchema . getElementType ( ) ) ; Iterator iter = array . iterator ( ) ; while ( iter . hasNext ( ) ) { newArray . add ( iter . next ( ) ) ; } fieldValue = newArray ; break ; } p . put ( fieldPos , fieldValue ) ; } } this . buffer . put ( key , p ) ; } private void addOrUpdateField ( K key , Field field , Object value ) { Schema schema = field . schema ( ) ; Type type = schema . getType ( ) ; switch ( type ) { case STRING : case BOOLEAN : case INT : case LONG : case BYTES : case FLOAT : case DOUBLE : case FIXED : this . cassandraClient . addColumn ( key , field . name ( ) , value ) ; break ; case RECORD : if ( value != null ) { if ( value instanceof PersistentBase ) { PersistentBase persistentBase = ( PersistentBase ) value ; for ( Field member : schema . getFields ( ) ) { Object memberValue = persistentBase . get ( member . pos ( ) ) ; if ( memberValue instanceof GenericArray < ? > ) { if ( ( ( GenericArray ) memberValue ) . size ( ) == <NUM_LIT:0> ) { continue ; } } else if ( memberValue instanceof StatefulHashMap < ? , ? > ) { if ( ( ( StatefulHashMap ) memberValue ) . size ( ) == <NUM_LIT:0> ) { continue ; } } this . cassandraClient . addSubColumn ( key , field . name ( ) , member . name ( ) , memberValue ) ; } } else { LOG . info ( "<STR_LIT>" + value . toString ( ) ) ; } } break ; case MAP : if ( value != null ) { if ( value instanceof StatefulHashMap < ? , ? > ) { this . cassandraClient . addStatefulHashMap ( key , field . name ( ) , ( StatefulHashMap < Utf8 , Object > ) value ) ; } else { LOG . info ( "<STR_LIT>" + value . toString ( ) ) ; } } break ; case ARRAY : if ( value != null ) { if ( value instanceof GenericArray < ? > ) { this . cassandraClient . addGenericArray ( key , field . name ( ) , ( GenericArray ) value ) ; } else { LOG . info ( "<STR_LIT>" + value . toString ( ) ) ; } } break ; default : LOG . info ( "<STR_LIT>" + type . name ( ) ) ; } } @ Override public boolean schemaExists ( ) throws IOException { LOG . info ( "<STR_LIT>" ) ; return cassandraClient . keyspaceExists ( ) ; } } </s>
|
<s> package org . apache . gora . cassandra . store ; import java . nio . ByteBuffer ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import me . prettyprint . cassandra . model . ConfigurableConsistencyLevel ; import me . prettyprint . cassandra . serializers . ByteBufferSerializer ; import me . prettyprint . cassandra . serializers . IntegerSerializer ; import me . prettyprint . cassandra . serializers . StringSerializer ; import me . prettyprint . cassandra . service . CassandraHostConfigurator ; import me . prettyprint . hector . api . Cluster ; import me . prettyprint . hector . api . Keyspace ; import me . prettyprint . hector . api . beans . OrderedRows ; import me . prettyprint . hector . api . beans . OrderedSuperRows ; import me . prettyprint . hector . api . beans . Row ; import me . prettyprint . hector . api . beans . SuperRow ; import me . prettyprint . hector . api . ddl . ColumnFamilyDefinition ; import me . prettyprint . hector . api . ddl . KeyspaceDefinition ; import me . prettyprint . hector . api . factory . HFactory ; import me . prettyprint . hector . api . mutation . Mutator ; import me . prettyprint . hector . api . query . QueryResult ; import me . prettyprint . hector . api . query . RangeSlicesQuery ; import me . prettyprint . hector . api . query . RangeSuperSlicesQuery ; import me . prettyprint . hector . api . HConsistencyLevel ; import me . prettyprint . hector . api . Serializer ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Type ; import org . apache . avro . generic . GenericArray ; import org . apache . avro . util . Utf8 ; import org . apache . gora . cassandra . query . CassandraQuery ; import org . apache . gora . cassandra . serializers . GenericArraySerializer ; import org . apache . gora . cassandra . serializers . GoraSerializerTypeInferer ; import org . apache . gora . cassandra . serializers . TypeUtils ; import org . apache . gora . mapreduce . GoraRecordReader ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . persistency . State ; import org . apache . gora . persistency . StatefulHashMap ; import org . apache . gora . query . Query ; import org . apache . gora . util . ByteUtils ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CassandraClient < K , T extends Persistent > { public static final Logger LOG = LoggerFactory . getLogger ( CassandraClient . class ) ; private Cluster cluster ; private Keyspace keyspace ; private Mutator < K > mutator ; private Class < K > keyClass ; private Class < T > persistentClass ; private CassandraMapping cassandraMapping = null ; private Serializer < K > keySerializer ; public void initialize ( Class < K > keyClass , Class < T > persistentClass ) throws Exception { this . keyClass = keyClass ; this . persistentClass = persistentClass ; this . cassandraMapping = CassandraMappingManager . getManager ( ) . get ( persistentClass ) ; this . cluster = HFactory . getOrCreateCluster ( this . cassandraMapping . getClusterName ( ) , new CassandraHostConfigurator ( this . cassandraMapping . getHostName ( ) ) ) ; checkKeyspace ( ) ; this . keyspace = HFactory . createKeyspace ( this . cassandraMapping . getKeyspaceName ( ) , this . cluster ) ; this . keySerializer = GoraSerializerTypeInferer . getSerializer ( keyClass ) ; this . mutator = HFactory . createMutator ( this . keyspace , this . keySerializer ) ; } public boolean keyspaceExists ( ) { KeyspaceDefinition keyspaceDefinition = this . cluster . describeKeyspace ( this . cassandraMapping . getKeyspaceName ( ) ) ; return ( keyspaceDefinition != null ) ; } public void checkKeyspace ( ) { KeyspaceDefinition keyspaceDefinition = this . cluster . describeKeyspace ( this . cassandraMapping . getKeyspaceName ( ) ) ; if ( keyspaceDefinition == null ) { List < ColumnFamilyDefinition > columnFamilyDefinitions = this . cassandraMapping . getColumnFamilyDefinitions ( ) ; keyspaceDefinition = HFactory . createKeyspaceDefinition ( this . cassandraMapping . getKeyspaceName ( ) , "<STR_LIT>" , <NUM_LIT:1> , columnFamilyDefinitions ) ; this . cluster . addKeyspace ( keyspaceDefinition , true ) ; ConfigurableConsistencyLevel configurableConsistencyLevel = new ConfigurableConsistencyLevel ( ) ; Map < String , HConsistencyLevel > clmap = new HashMap < String , HConsistencyLevel > ( ) ; clmap . put ( "<STR_LIT>" , HConsistencyLevel . ONE ) ; configurableConsistencyLevel . setReadCfConsistencyLevels ( clmap ) ; configurableConsistencyLevel . setWriteCfConsistencyLevels ( clmap ) ; HFactory . createKeyspace ( "<STR_LIT>" , this . cluster , configurableConsistencyLevel ) ; keyspaceDefinition = null ; } } public void dropKeyspace ( ) { this . cluster . dropKeyspace ( this . cassandraMapping . getKeyspaceName ( ) ) ; } public void addColumn ( K key , String fieldName , Object value ) { if ( value == null ) { return ; } ByteBuffer byteBuffer = toByteBuffer ( value ) ; String columnFamily = this . cassandraMapping . getFamily ( fieldName ) ; String columnName = this . cassandraMapping . getColumn ( fieldName ) ; if ( columnName == null ) { LOG . warn ( "<STR_LIT>" + fieldName + "<STR_LIT>" + value . toString ( ) ) ; return ; } HectorUtils . insertColumn ( mutator , key , columnFamily , columnName , byteBuffer ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public void addSubColumn ( K key , String fieldName , ByteBuffer columnName , Object value ) { if ( value == null ) { return ; } ByteBuffer byteBuffer = toByteBuffer ( value ) ; String columnFamily = this . cassandraMapping . getFamily ( fieldName ) ; String superColumnName = this . cassandraMapping . getColumn ( fieldName ) ; HectorUtils . insertSubColumn ( mutator , key , columnFamily , superColumnName , columnName , byteBuffer ) ; } public void addSubColumn ( K key , String fieldName , String columnName , Object value ) { addSubColumn ( key , fieldName , StringSerializer . get ( ) . toByteBuffer ( columnName ) , value ) ; } public void addSubColumn ( K key , String fieldName , Integer columnName , Object value ) { addSubColumn ( key , fieldName , IntegerSerializer . get ( ) . toByteBuffer ( columnName ) , value ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public void deleteSubColumn ( K key , String fieldName , ByteBuffer columnName ) { String columnFamily = this . cassandraMapping . getFamily ( fieldName ) ; String superColumnName = this . cassandraMapping . getColumn ( fieldName ) ; HectorUtils . deleteSubColumn ( mutator , key , columnFamily , superColumnName , columnName ) ; } public void deleteSubColumn ( K key , String fieldName , String columnName ) { deleteSubColumn ( key , fieldName , StringSerializer . get ( ) . toByteBuffer ( columnName ) ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public void addGenericArray ( K key , String fieldName , GenericArray array ) { if ( isSuper ( cassandraMapping . getFamily ( fieldName ) ) ) { int i = <NUM_LIT:0> ; for ( Object itemValue : array ) { if ( itemValue instanceof GenericArray < ? > ) { if ( ( ( GenericArray ) itemValue ) . size ( ) == <NUM_LIT:0> ) { continue ; } } else if ( itemValue instanceof StatefulHashMap < ? , ? > ) { if ( ( ( StatefulHashMap ) itemValue ) . size ( ) == <NUM_LIT:0> ) { continue ; } } addSubColumn ( key , fieldName , i ++ , itemValue ) ; } } else { addColumn ( key , fieldName , array ) ; } } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public void addStatefulHashMap ( K key , String fieldName , StatefulHashMap < Utf8 , Object > map ) { if ( isSuper ( cassandraMapping . getFamily ( fieldName ) ) ) { int i = <NUM_LIT:0> ; for ( Utf8 mapKey : map . keySet ( ) ) { if ( map . getState ( mapKey ) == State . DELETED ) { deleteSubColumn ( key , fieldName , mapKey . toString ( ) ) ; continue ; } Object mapValue = map . get ( mapKey ) ; if ( mapValue instanceof GenericArray < ? > ) { if ( ( ( GenericArray ) mapValue ) . size ( ) == <NUM_LIT:0> ) { continue ; } } else if ( mapValue instanceof StatefulHashMap < ? , ? > ) { if ( ( ( StatefulHashMap ) mapValue ) . size ( ) == <NUM_LIT:0> ) { continue ; } } addSubColumn ( key , fieldName , mapKey . toString ( ) , mapValue ) ; } } else { addColumn ( key , fieldName , map ) ; } } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public ByteBuffer toByteBuffer ( Object value ) { ByteBuffer byteBuffer = null ; Serializer serializer = GoraSerializerTypeInferer . getSerializer ( value ) ; if ( serializer == null ) { LOG . info ( "<STR_LIT>" + value . toString ( ) ) ; } else { byteBuffer = serializer . toByteBuffer ( value ) ; } if ( byteBuffer == null ) { LOG . info ( "<STR_LIT>" + value . getClass ( ) . getName ( ) + "<STR_LIT>" + value + "<STR_LIT>" ) ; } return byteBuffer ; } public List < Row < K , ByteBuffer , ByteBuffer > > execute ( CassandraQuery < K , T > cassandraQuery , String family ) { String [ ] columnNames = cassandraQuery . getColumns ( family ) ; ByteBuffer [ ] columnNameByteBuffers = new ByteBuffer [ columnNames . length ] ; for ( int i = <NUM_LIT:0> ; i < columnNames . length ; i ++ ) { columnNameByteBuffers [ i ] = StringSerializer . get ( ) . toByteBuffer ( columnNames [ i ] ) ; } Query < K , T > query = cassandraQuery . getQuery ( ) ; int limit = ( int ) query . getLimit ( ) ; if ( limit < <NUM_LIT:1> ) { limit = Integer . MAX_VALUE ; } K startKey = query . getStartKey ( ) ; K endKey = query . getEndKey ( ) ; RangeSlicesQuery < K , ByteBuffer , ByteBuffer > rangeSlicesQuery = HFactory . createRangeSlicesQuery ( this . keyspace , this . keySerializer , ByteBufferSerializer . get ( ) , ByteBufferSerializer . get ( ) ) ; rangeSlicesQuery . setColumnFamily ( family ) ; rangeSlicesQuery . setKeys ( startKey , endKey ) ; rangeSlicesQuery . setRange ( ByteBuffer . wrap ( new byte [ <NUM_LIT:0> ] ) , ByteBuffer . wrap ( new byte [ <NUM_LIT:0> ] ) , false , GoraRecordReader . BUFFER_LIMIT_READ_VALUE ) ; rangeSlicesQuery . setRowCount ( limit ) ; rangeSlicesQuery . setColumnNames ( columnNameByteBuffers ) ; QueryResult < OrderedRows < K , ByteBuffer , ByteBuffer > > queryResult = rangeSlicesQuery . execute ( ) ; OrderedRows < K , ByteBuffer , ByteBuffer > orderedRows = queryResult . get ( ) ; return orderedRows . getList ( ) ; } public Map < String , List < String > > getFamilyMap ( Query < K , T > query ) { Map < String , List < String > > map = new HashMap < String , List < String > > ( ) ; for ( String field : query . getFields ( ) ) { String family = this . cassandraMapping . getFamily ( field ) ; String column = this . cassandraMapping . getColumn ( field ) ; List < String > list = map . get ( family ) ; if ( list == null ) { list = new ArrayList < String > ( ) ; map . put ( family , list ) ; } if ( column != null ) { list . add ( column ) ; } } return map ; } public Map < String , String > getReverseMap ( Query < K , T > query ) { Map < String , String > map = new HashMap < String , String > ( ) ; for ( String field : query . getFields ( ) ) { String family = this . cassandraMapping . getFamily ( field ) ; String column = this . cassandraMapping . getColumn ( field ) ; map . put ( family + "<STR_LIT::>" + column , field ) ; } return map ; } public boolean isSuper ( String family ) { return this . cassandraMapping . isSuper ( family ) ; } public List < SuperRow < K , String , ByteBuffer , ByteBuffer > > executeSuper ( CassandraQuery < K , T > cassandraQuery , String family ) { String [ ] columnNames = cassandraQuery . getColumns ( family ) ; Query < K , T > query = cassandraQuery . getQuery ( ) ; int limit = ( int ) query . getLimit ( ) ; if ( limit < <NUM_LIT:1> ) { limit = Integer . MAX_VALUE ; } K startKey = query . getStartKey ( ) ; K endKey = query . getEndKey ( ) ; RangeSuperSlicesQuery < K , String , ByteBuffer , ByteBuffer > rangeSuperSlicesQuery = HFactory . createRangeSuperSlicesQuery ( this . keyspace , this . keySerializer , StringSerializer . get ( ) , ByteBufferSerializer . get ( ) , ByteBufferSerializer . get ( ) ) ; rangeSuperSlicesQuery . setColumnFamily ( family ) ; rangeSuperSlicesQuery . setKeys ( startKey , endKey ) ; rangeSuperSlicesQuery . setRange ( "<STR_LIT>" , "<STR_LIT>" , false , GoraRecordReader . BUFFER_LIMIT_READ_VALUE ) ; rangeSuperSlicesQuery . setRowCount ( limit ) ; rangeSuperSlicesQuery . setColumnNames ( columnNames ) ; QueryResult < OrderedSuperRows < K , String , ByteBuffer , ByteBuffer > > queryResult = rangeSuperSlicesQuery . execute ( ) ; OrderedSuperRows < K , String , ByteBuffer , ByteBuffer > orderedRows = queryResult . get ( ) ; return orderedRows . getList ( ) ; } public String getKeyspaceName ( ) { return this . cassandraMapping . getKeyspaceName ( ) ; } } </s>
|
<s> package org . apache . gora . cassandra . store ; import java . nio . ByteBuffer ; import java . util . Arrays ; import me . prettyprint . cassandra . serializers . ByteBufferSerializer ; import me . prettyprint . cassandra . serializers . IntegerSerializer ; import me . prettyprint . cassandra . serializers . StringSerializer ; import me . prettyprint . hector . api . beans . HColumn ; import me . prettyprint . hector . api . beans . HSuperColumn ; import me . prettyprint . hector . api . factory . HFactory ; import me . prettyprint . hector . api . mutation . Mutator ; import me . prettyprint . hector . api . Serializer ; import org . apache . gora . persistency . Persistent ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class HectorUtils < K , T extends Persistent > { public static final Logger LOG = LoggerFactory . getLogger ( HectorUtils . class ) ; public static < K > void insertColumn ( Mutator < K > mutator , K key , String columnFamily , ByteBuffer columnName , ByteBuffer columnValue ) { mutator . insert ( key , columnFamily , createColumn ( columnName , columnValue ) ) ; } public static < K > void insertColumn ( Mutator < K > mutator , K key , String columnFamily , String columnName , ByteBuffer columnValue ) { mutator . insert ( key , columnFamily , createColumn ( columnName , columnValue ) ) ; } public static < K > HColumn < ByteBuffer , ByteBuffer > createColumn ( ByteBuffer name , ByteBuffer value ) { return HFactory . createColumn ( name , value , ByteBufferSerializer . get ( ) , ByteBufferSerializer . get ( ) ) ; } public static < K > HColumn < String , ByteBuffer > createColumn ( String name , ByteBuffer value ) { return HFactory . createColumn ( name , value , StringSerializer . get ( ) , ByteBufferSerializer . get ( ) ) ; } public static < K > HColumn < Integer , ByteBuffer > createColumn ( Integer name , ByteBuffer value ) { return HFactory . createColumn ( name , value , IntegerSerializer . get ( ) , ByteBufferSerializer . get ( ) ) ; } public static < K > void insertSubColumn ( Mutator < K > mutator , K key , String columnFamily , String superColumnName , ByteBuffer columnName , ByteBuffer columnValue ) { mutator . insert ( key , columnFamily , createSuperColumn ( superColumnName , columnName , columnValue ) ) ; } public static < K > void insertSubColumn ( Mutator < K > mutator , K key , String columnFamily , String superColumnName , String columnName , ByteBuffer columnValue ) { mutator . insert ( key , columnFamily , createSuperColumn ( superColumnName , columnName , columnValue ) ) ; } public static < K > void insertSubColumn ( Mutator < K > mutator , K key , String columnFamily , String superColumnName , Integer columnName , ByteBuffer columnValue ) { mutator . insert ( key , columnFamily , createSuperColumn ( superColumnName , columnName , columnValue ) ) ; } public static < K > void deleteSubColumn ( Mutator < K > mutator , K key , String columnFamily , String superColumnName , ByteBuffer columnName ) { mutator . subDelete ( key , columnFamily , superColumnName , columnName , StringSerializer . get ( ) , ByteBufferSerializer . get ( ) ) ; } public static < K > HSuperColumn < String , ByteBuffer , ByteBuffer > createSuperColumn ( String superColumnName , ByteBuffer columnName , ByteBuffer columnValue ) { return HFactory . createSuperColumn ( superColumnName , Arrays . asList ( createColumn ( columnName , columnValue ) ) , StringSerializer . get ( ) , ByteBufferSerializer . get ( ) , ByteBufferSerializer . get ( ) ) ; } public static < K > HSuperColumn < String , String , ByteBuffer > createSuperColumn ( String superColumnName , String columnName , ByteBuffer columnValue ) { return HFactory . createSuperColumn ( superColumnName , Arrays . asList ( createColumn ( columnName , columnValue ) ) , StringSerializer . get ( ) , StringSerializer . get ( ) , ByteBufferSerializer . get ( ) ) ; } public static < K > HSuperColumn < String , Integer , ByteBuffer > createSuperColumn ( String superColumnName , Integer columnName , ByteBuffer columnValue ) { return HFactory . createSuperColumn ( superColumnName , Arrays . asList ( createColumn ( columnName , columnValue ) ) , StringSerializer . get ( ) , IntegerSerializer . get ( ) , ByteBufferSerializer . get ( ) ) ; } } </s>
|
<s> package org . apache . gora . cassandra . store ; import java . io . IOException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import me . prettyprint . cassandra . model . BasicColumnFamilyDefinition ; import me . prettyprint . cassandra . service . ThriftCfDef ; import me . prettyprint . hector . api . ddl . ColumnFamilyDefinition ; import me . prettyprint . hector . api . ddl . ColumnType ; import me . prettyprint . hector . api . ddl . ComparatorType ; import org . jdom . Document ; import org . jdom . Element ; import org . jdom . JDOMException ; import org . jdom . input . SAXBuilder ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class CassandraMappingManager { public static final Logger LOG = LoggerFactory . getLogger ( CassandraMappingManager . class ) ; private static final String MAPPING_FILE = "<STR_LIT>" ; private static final String KEYSPACE_ELEMENT = "<STR_LIT>" ; private static final String NAME_ATTRIBUTE = "<STR_LIT:name>" ; private static final String MAPPING_ELEMENT = "<STR_LIT:class>" ; private static final String COLUMN_ATTRIBUTE = "<STR_LIT>" ; private static final String FAMILY_ATTRIBUTE = "<STR_LIT>" ; private static final String SUPER_ATTRIBUTE = "<STR_LIT:type>" ; private static final String CLUSTER_ATTRIBUTE = "<STR_LIT>" ; private static final String HOST_ATTRIBUTE = "<STR_LIT>" ; private static CassandraMappingManager manager = new CassandraMappingManager ( ) ; public static CassandraMappingManager getManager ( ) { return manager ; } private Map < String , Element > keyspaceMap = null ; private Map < String , Element > mappingMap = null ; private CassandraMappingManager ( ) { keyspaceMap = new HashMap < String , Element > ( ) ; mappingMap = new HashMap < String , Element > ( ) ; try { loadConfiguration ( ) ; } catch ( JDOMException e ) { LOG . error ( e . toString ( ) ) ; } catch ( IOException e ) { LOG . error ( e . toString ( ) ) ; } } public CassandraMapping get ( Class persistentClass ) { String className = persistentClass . getName ( ) ; Element mappingElement = mappingMap . get ( className ) ; String keyspaceName = mappingElement . getAttributeValue ( KEYSPACE_ELEMENT ) ; Element keyspaceElement = keyspaceMap . get ( keyspaceName ) ; return new CassandraMapping ( keyspaceElement , mappingElement ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public void loadConfiguration ( ) throws JDOMException , IOException { SAXBuilder saxBuilder = new SAXBuilder ( ) ; Document document = saxBuilder . build ( getClass ( ) . getClassLoader ( ) . getResourceAsStream ( MAPPING_FILE ) ) ; if ( document == null ) { LOG . warn ( "<STR_LIT>" + MAPPING_FILE + "<STR_LIT>" ) ; } Element root = document . getRootElement ( ) ; List < Element > keyspaces = root . getChildren ( KEYSPACE_ELEMENT ) ; if ( keyspaces == null || keyspaces . size ( ) == <NUM_LIT:0> ) { LOG . warn ( "<STR_LIT>" ) ; } else { LOG . info ( "<STR_LIT>" + KEYSPACE_ELEMENT + "<STR_LIT:'>" ) ; for ( Element keyspace : keyspaces ) { String keyspaceName = keyspace . getAttributeValue ( NAME_ATTRIBUTE ) ; if ( keyspaceName == null ) { LOG . warn ( "<STR_LIT>" ) ; } LOG . info ( "<STR_LIT>" + NAME_ATTRIBUTE + "<STR_LIT:'>" ) ; keyspaceMap . put ( keyspaceName , keyspace ) ; } } List < Element > mappings = root . getChildren ( MAPPING_ELEMENT ) ; if ( mappings == null || mappings . size ( ) == <NUM_LIT:0> ) { LOG . warn ( "<STR_LIT>" ) ; } else { LOG . info ( "<STR_LIT>" + MAPPING_ELEMENT + "<STR_LIT:'>" ) ; for ( Element mapping : mappings ) { String className = mapping . getAttributeValue ( NAME_ATTRIBUTE ) ; if ( className == null ) { LOG . warn ( "<STR_LIT>" ) ; continue ; } LOG . info ( "<STR_LIT>" + NAME_ATTRIBUTE + "<STR_LIT:'>" ) ; mappingMap . put ( className , mapping ) ; } } } } </s>
|
<s> package org . apache . gora . cassandra . serializers ; import java . nio . BufferUnderflowException ; import java . nio . ByteBuffer ; import java . util . HashMap ; import java . util . Map ; import me . prettyprint . cassandra . serializers . AbstractSerializer ; import me . prettyprint . cassandra . serializers . BytesArraySerializer ; import me . prettyprint . hector . api . Serializer ; import me . prettyprint . hector . api . ddl . ComparatorType ; import static me . prettyprint . hector . api . ddl . ComparatorType . BYTESTYPE ; import org . apache . avro . specific . SpecificFixed ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Type ; import org . apache . avro . util . Utf8 ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class SpecificFixedSerializer extends AbstractSerializer < SpecificFixed > { public static final Logger LOG = LoggerFactory . getLogger ( SpecificFixedSerializer . class ) ; private static SpecificFixedSerializer serializer = new SpecificFixedSerializer ( SpecificFixed . class ) ; public static SpecificFixedSerializer get ( ) { return serializer ; } private static Map < Class , SpecificFixedSerializer > classToSerializerMap = new HashMap < Class , SpecificFixedSerializer > ( ) ; public static SpecificFixedSerializer get ( Class clazz ) { SpecificFixedSerializer serializer = classToSerializerMap . get ( clazz ) ; if ( serializer == null ) { serializer = new SpecificFixedSerializer ( clazz ) ; classToSerializerMap . put ( clazz , serializer ) ; } return serializer ; } private Class < ? extends SpecificFixed > clazz ; public SpecificFixedSerializer ( Class < ? extends SpecificFixed > clazz ) { this . clazz = clazz ; } @ Override public ByteBuffer toByteBuffer ( SpecificFixed fixed ) { if ( fixed == null ) { return null ; } byte [ ] bytes = fixed . bytes ( ) ; if ( bytes . length < <NUM_LIT:1> ) { return null ; } return BytesArraySerializer . get ( ) . toByteBuffer ( bytes ) ; } @ Override public SpecificFixed fromByteBuffer ( ByteBuffer byteBuffer ) { if ( byteBuffer == null ) { return null ; } Object value = null ; try { value = clazz . newInstance ( ) ; } catch ( InstantiationException ie ) { LOG . warn ( "<STR_LIT>" + clazz , ie ) ; return null ; } catch ( IllegalAccessException iae ) { LOG . warn ( "<STR_LIT>" + clazz , iae ) ; return null ; } if ( ! ( value instanceof SpecificFixed ) ) { LOG . warn ( "<STR_LIT>" ) ; return null ; } SpecificFixed fixed = ( SpecificFixed ) value ; byte [ ] bytes = fixed . bytes ( ) ; try { byteBuffer . get ( bytes , <NUM_LIT:0> , bytes . length ) ; } catch ( BufferUnderflowException e ) { throw e ; } fixed . bytes ( bytes ) ; return fixed ; } @ Override public ComparatorType getComparatorType ( ) { return BYTESTYPE ; } } </s>
|
<s> package org . apache . gora . cassandra . serializers ; import java . nio . ByteBuffer ; import me . prettyprint . cassandra . serializers . AbstractSerializer ; import me . prettyprint . cassandra . serializers . StringSerializer ; import me . prettyprint . hector . api . ddl . ComparatorType ; import static me . prettyprint . hector . api . ddl . ComparatorType . UTF8TYPE ; import org . apache . avro . util . Utf8 ; public final class Utf8Serializer extends AbstractSerializer < Utf8 > { private static final Utf8Serializer instance = new Utf8Serializer ( ) ; public static Utf8Serializer get ( ) { return instance ; } @ Override public ByteBuffer toByteBuffer ( Utf8 obj ) { if ( obj == null ) { return null ; } return StringSerializer . get ( ) . toByteBuffer ( obj . toString ( ) ) ; } @ Override public Utf8 fromByteBuffer ( ByteBuffer byteBuffer ) { if ( byteBuffer == null ) { return null ; } return new Utf8 ( StringSerializer . get ( ) . fromByteBuffer ( byteBuffer ) ) ; } @ Override public ComparatorType getComparatorType ( ) { return UTF8TYPE ; } } </s>
|
<s> package org . apache . gora . cassandra . serializers ; import java . nio . BufferUnderflowException ; import java . nio . ByteBuffer ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import me . prettyprint . cassandra . serializers . AbstractSerializer ; import me . prettyprint . cassandra . serializers . BytesArraySerializer ; import me . prettyprint . cassandra . serializers . IntegerSerializer ; import me . prettyprint . hector . api . Serializer ; import me . prettyprint . hector . api . ddl . ComparatorType ; import static me . prettyprint . hector . api . ddl . ComparatorType . UTF8TYPE ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Type ; import org . apache . avro . generic . GenericArray ; import org . apache . avro . specific . SpecificFixed ; import org . apache . avro . util . Utf8 ; import org . apache . gora . persistency . ListGenericArray ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class GenericArraySerializer < T > extends AbstractSerializer < GenericArray < T > > { public static final Logger LOG = LoggerFactory . getLogger ( GenericArraySerializer . class ) ; private static Map < Type , GenericArraySerializer > elementTypeToSerializerMap = new HashMap < Type , GenericArraySerializer > ( ) ; private static Map < Class , GenericArraySerializer > fixedClassToSerializerMap = new HashMap < Class , GenericArraySerializer > ( ) ; public static GenericArraySerializer get ( Type elementType ) { GenericArraySerializer serializer = elementTypeToSerializerMap . get ( elementType ) ; if ( serializer == null ) { serializer = new GenericArraySerializer ( elementType ) ; elementTypeToSerializerMap . put ( elementType , serializer ) ; } return serializer ; } public static GenericArraySerializer get ( Type elementType , Class clazz ) { if ( elementType != Type . FIXED ) { return null ; } GenericArraySerializer serializer = elementTypeToSerializerMap . get ( clazz ) ; if ( serializer == null ) { serializer = new GenericArraySerializer ( clazz ) ; fixedClassToSerializerMap . put ( clazz , serializer ) ; } return serializer ; } public static GenericArraySerializer get ( Schema elementSchema ) { Type type = elementSchema . getType ( ) ; if ( type == Type . FIXED ) { return get ( Type . FIXED , TypeUtils . getClass ( elementSchema ) ) ; } else { return get ( type ) ; } } private Schema elementSchema = null ; private Type elementType = null ; private int size = - <NUM_LIT:1> ; private Class < T > clazz = null ; private Serializer < T > elementSerializer = null ; public GenericArraySerializer ( Serializer < T > elementSerializer ) { this . elementSerializer = elementSerializer ; } public GenericArraySerializer ( Schema elementSchema ) { this . elementSchema = elementSchema ; elementType = elementSchema . getType ( ) ; size = TypeUtils . getFixedSize ( elementSchema ) ; elementSerializer = GoraSerializerTypeInferer . getSerializer ( elementSchema ) ; } public GenericArraySerializer ( Type elementType ) { this . elementType = elementType ; if ( elementType != Type . FIXED ) { elementSchema = Schema . create ( elementType ) ; } clazz = TypeUtils . getClass ( elementType ) ; size = TypeUtils . getFixedSize ( elementType ) ; elementSerializer = GoraSerializerTypeInferer . getSerializer ( elementType ) ; } public GenericArraySerializer ( Class < T > clazz ) { this . clazz = clazz ; elementType = TypeUtils . getType ( clazz ) ; size = TypeUtils . getFixedSize ( clazz ) ; if ( elementType == null || elementType == Type . FIXED ) { elementType = Type . FIXED ; elementSchema = TypeUtils . getSchema ( clazz ) ; elementSerializer = GoraSerializerTypeInferer . getSerializer ( elementType , clazz ) ; } else { elementSerializer = GoraSerializerTypeInferer . getSerializer ( elementType ) ; } } @ Override public ByteBuffer toByteBuffer ( GenericArray < T > array ) { if ( array == null ) { return null ; } if ( size > <NUM_LIT:0> ) { return toByteBufferWithFixedLengthElements ( array ) ; } else { return toByteBufferWithVariableLengthElements ( array ) ; } } private ByteBuffer toByteBufferWithFixedLengthElements ( GenericArray < T > array ) { ByteBuffer byteBuffer = ByteBuffer . allocate ( ( int ) array . size ( ) * size ) ; for ( T element : array ) { byteBuffer . put ( elementSerializer . toByteBuffer ( element ) ) ; } byteBuffer . rewind ( ) ; return byteBuffer ; } private ByteBuffer toByteBufferWithVariableLengthElements ( GenericArray < T > array ) { int n = ( int ) array . size ( ) ; List < byte [ ] > list = new ArrayList < byte [ ] > ( n ) ; n *= <NUM_LIT:4> ; for ( T element : array ) { byte [ ] bytes = BytesArraySerializer . get ( ) . fromByteBuffer ( elementSerializer . toByteBuffer ( element ) ) ; list . add ( bytes ) ; n += bytes . length ; } ByteBuffer byteBuffer = ByteBuffer . allocate ( n ) ; for ( byte [ ] bytes : list ) { byteBuffer . put ( IntegerSerializer . get ( ) . toByteBuffer ( bytes . length ) ) ; byteBuffer . put ( BytesArraySerializer . get ( ) . toByteBuffer ( bytes ) ) ; } byteBuffer . rewind ( ) ; return byteBuffer ; } @ Override public GenericArray < T > fromByteBuffer ( ByteBuffer byteBuffer ) { if ( byteBuffer == null ) { return null ; } GenericArray < T > array = new ListGenericArray < T > ( elementSchema ) ; int i = <NUM_LIT:0> ; while ( true ) { T element = null ; try { if ( size > <NUM_LIT:0> ) { element = elementSerializer . fromByteBuffer ( byteBuffer ) ; } else { int n = IntegerSerializer . get ( ) . fromByteBuffer ( byteBuffer ) ; byte [ ] bytes = new byte [ n ] ; byteBuffer . get ( bytes , <NUM_LIT:0> , n ) ; element = elementSerializer . fromByteBuffer ( BytesArraySerializer . get ( ) . toByteBuffer ( bytes ) ) ; } } catch ( BufferUnderflowException e ) { break ; } if ( element == null ) { break ; } array . add ( element ) ; } return array ; } @ Override public ComparatorType getComparatorType ( ) { return elementSerializer . getComparatorType ( ) ; } } </s>
|
<s> package org . apache . gora . cassandra . serializers ; import java . nio . ByteBuffer ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Type ; import org . apache . avro . generic . GenericArray ; import org . apache . avro . specific . SpecificFixed ; import org . apache . avro . util . Utf8 ; import org . apache . gora . persistency . ListGenericArray ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . persistency . StatefulHashMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class TypeUtils { public static final Logger LOG = LoggerFactory . getLogger ( TypeUtils . class ) ; public static Class getClass ( Object value ) { return value . getClass ( ) ; } public static Schema getSchema ( Object value ) { if ( value instanceof GenericArray ) { return Schema . createArray ( getElementSchema ( ( GenericArray ) value ) ) ; } else { return getSchema ( getClass ( value ) ) ; } } public static Type getType ( Object value ) { return getType ( getClass ( value ) ) ; } public static Type getType ( Class < ? > clazz ) { if ( clazz . equals ( Utf8 . class ) ) { return Type . STRING ; } else if ( clazz . equals ( Boolean . class ) || clazz . equals ( boolean . class ) ) { return Type . BOOLEAN ; } else if ( clazz . equals ( ByteBuffer . class ) ) { return Type . BYTES ; } else if ( clazz . equals ( Double . class ) || clazz . equals ( double . class ) ) { return Type . DOUBLE ; } else if ( clazz . equals ( Float . class ) || clazz . equals ( float . class ) ) { return Type . FLOAT ; } else if ( clazz . equals ( Integer . class ) || clazz . equals ( int . class ) ) { return Type . INT ; } else if ( clazz . equals ( Long . class ) || clazz . equals ( long . class ) ) { return Type . LONG ; } else if ( clazz . equals ( ListGenericArray . class ) ) { return Type . ARRAY ; } else if ( clazz . equals ( StatefulHashMap . class ) ) { return Type . MAP ; } else if ( clazz . equals ( Persistent . class ) ) { return Type . RECORD ; } else if ( clazz . getSuperclass ( ) . equals ( SpecificFixed . class ) ) { return Type . FIXED ; } else { return null ; } } public static Class getClass ( Type type ) { if ( type == Type . STRING ) { return Utf8 . class ; } else if ( type == Type . BOOLEAN ) { return Boolean . class ; } else if ( type == Type . BYTES ) { return ByteBuffer . class ; } else if ( type == Type . DOUBLE ) { return Double . class ; } else if ( type == Type . FLOAT ) { return Float . class ; } else if ( type == Type . INT ) { return Integer . class ; } else if ( type == Type . LONG ) { return Long . class ; } else if ( type == Type . ARRAY ) { return ListGenericArray . class ; } else if ( type == Type . MAP ) { return StatefulHashMap . class ; } else if ( type == Type . RECORD ) { return Persistent . class ; } else if ( type == Type . FIXED ) { return null ; } else { return null ; } } public static Schema getSchema ( Class clazz ) { Type type = getType ( clazz ) ; if ( type == null ) { return null ; } else if ( type == Type . FIXED ) { int size = getFixedSize ( clazz ) ; String name = clazz . getName ( ) ; String space = null ; int n = name . lastIndexOf ( "<STR_LIT:.>" ) ; if ( n < <NUM_LIT:0> ) { space = name . substring ( <NUM_LIT:0> , n ) ; name = name . substring ( n + <NUM_LIT:1> ) ; } else { space = null ; } String doc = null ; return Schema . createFixed ( name , doc , space , size ) ; } else if ( type == Type . ARRAY ) { Object obj = null ; try { obj = clazz . newInstance ( ) ; } catch ( InstantiationException e ) { LOG . warn ( e . toString ( ) ) ; return null ; } catch ( IllegalAccessException e ) { LOG . warn ( e . toString ( ) ) ; return null ; } return getSchema ( obj ) ; } else if ( type == Type . MAP ) { return null ; } else if ( type == Type . RECORD ) { return null ; } else { return Schema . create ( type ) ; } } public static Class getClass ( Schema schema ) { Type type = schema . getType ( ) ; if ( type == null ) { return null ; } else if ( type == Type . FIXED ) { try { return Class . forName ( schema . getFullName ( ) ) ; } catch ( ClassNotFoundException e ) { LOG . warn ( e . toString ( ) + "<STR_LIT:U+0020:U+0020>" + schema ) ; return null ; } } else { return getClass ( type ) ; } } public static int getFixedSize ( Type type ) { if ( type == Type . BOOLEAN ) { return <NUM_LIT:1> ; } else if ( type == Type . DOUBLE ) { return <NUM_LIT:8> ; } else if ( type == Type . FLOAT ) { return <NUM_LIT:4> ; } else if ( type == Type . INT ) { return <NUM_LIT:4> ; } else if ( type == Type . LONG ) { return <NUM_LIT:8> ; } else { return - <NUM_LIT:1> ; } } public static int getFixedSize ( Schema schema ) { Type type = schema . getType ( ) ; if ( type == Type . FIXED ) { return schema . getFixedSize ( ) ; } else { return getFixedSize ( type ) ; } } public static int getFixedSize ( Class clazz ) { Type type = getType ( clazz ) ; if ( type == Type . FIXED ) { try { return ( ( SpecificFixed ) clazz . newInstance ( ) ) . bytes ( ) . length ; } catch ( InstantiationException e ) { LOG . warn ( e . toString ( ) ) ; return - <NUM_LIT:1> ; } catch ( IllegalAccessException e ) { LOG . warn ( e . toString ( ) ) ; return - <NUM_LIT:1> ; } } else { return getFixedSize ( type ) ; } } public static Schema getElementSchema ( GenericArray array ) { Schema schema = array . getSchema ( ) ; return ( schema . getType ( ) == Type . ARRAY ) ? schema . getElementType ( ) : schema ; } public static Type getElementType ( ListGenericArray array ) { return getElementSchema ( array ) . getType ( ) ; } } </s>
|
<s> package org . apache . gora . cassandra . serializers ; import java . nio . ByteBuffer ; import me . prettyprint . cassandra . serializers . BytesArraySerializer ; import me . prettyprint . cassandra . serializers . ByteBufferSerializer ; import me . prettyprint . cassandra . serializers . BooleanSerializer ; import me . prettyprint . cassandra . serializers . DoubleSerializer ; import me . prettyprint . cassandra . serializers . FloatSerializer ; import me . prettyprint . cassandra . serializers . IntegerSerializer ; import me . prettyprint . cassandra . serializers . LongSerializer ; import me . prettyprint . cassandra . serializers . StringSerializer ; import me . prettyprint . cassandra . serializers . SerializerTypeInferer ; import me . prettyprint . hector . api . Serializer ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Type ; import org . apache . avro . generic . GenericArray ; import org . apache . avro . specific . SpecificFixed ; import org . apache . avro . util . Utf8 ; import org . apache . gora . persistency . StatefulHashMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class GoraSerializerTypeInferer { public static final Logger LOG = LoggerFactory . getLogger ( GoraSerializerTypeInferer . class ) ; @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) public static < T > Serializer < T > getSerializer ( Object value ) { Serializer serializer = null ; if ( value == null ) { serializer = ByteBufferSerializer . get ( ) ; } else if ( value instanceof Utf8 ) { serializer = Utf8Serializer . get ( ) ; } else if ( value instanceof Boolean ) { serializer = BooleanSerializer . get ( ) ; } else if ( value instanceof ByteBuffer ) { serializer = ByteBufferSerializer . get ( ) ; } else if ( value instanceof byte [ ] ) { serializer = BytesArraySerializer . get ( ) ; } else if ( value instanceof Double ) { serializer = DoubleSerializer . get ( ) ; } else if ( value instanceof Float ) { serializer = FloatSerializer . get ( ) ; } else if ( value instanceof Integer ) { serializer = IntegerSerializer . get ( ) ; } else if ( value instanceof Long ) { serializer = LongSerializer . get ( ) ; } else if ( value instanceof String ) { serializer = StringSerializer . get ( ) ; } else if ( value instanceof SpecificFixed ) { serializer = SpecificFixedSerializer . get ( value . getClass ( ) ) ; } else if ( value instanceof GenericArray ) { Schema schema = ( ( GenericArray ) value ) . getSchema ( ) ; if ( schema . getType ( ) == Type . ARRAY ) { schema = schema . getElementType ( ) ; } serializer = GenericArraySerializer . get ( schema ) ; } else if ( value instanceof StatefulHashMap ) { StatefulHashMap map = ( StatefulHashMap ) value ; if ( map . size ( ) == <NUM_LIT:0> ) { serializer = ByteBufferSerializer . get ( ) ; } else { Object value0 = map . values ( ) . iterator ( ) . next ( ) ; Schema schema = TypeUtils . getSchema ( value0 ) ; serializer = StatefulHashMapSerializer . get ( schema ) ; } } else { serializer = SerializerTypeInferer . getSerializer ( value ) ; } return serializer ; } @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) public static < T > Serializer < T > getSerializer ( Class < ? > valueClass ) { Serializer serializer = null ; if ( valueClass . equals ( Utf8 . class ) ) { serializer = Utf8Serializer . get ( ) ; } else if ( valueClass . equals ( Boolean . class ) || valueClass . equals ( boolean . class ) ) { serializer = BooleanSerializer . get ( ) ; } else if ( valueClass . equals ( ByteBuffer . class ) ) { serializer = ByteBufferSerializer . get ( ) ; } else if ( valueClass . equals ( Double . class ) || valueClass . equals ( double . class ) ) { serializer = DoubleSerializer . get ( ) ; } else if ( valueClass . equals ( Float . class ) || valueClass . equals ( float . class ) ) { serializer = FloatSerializer . get ( ) ; } else if ( valueClass . equals ( Integer . class ) || valueClass . equals ( int . class ) ) { serializer = IntegerSerializer . get ( ) ; } else if ( valueClass . equals ( Long . class ) || valueClass . equals ( long . class ) ) { serializer = LongSerializer . get ( ) ; } else if ( valueClass . equals ( String . class ) ) { serializer = StringSerializer . get ( ) ; } else { serializer = SerializerTypeInferer . getSerializer ( valueClass ) ; } return serializer ; } @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) public static < T > Serializer < T > getSerializer ( Schema schema ) { Serializer serializer = null ; Type type = schema . getType ( ) ; if ( type == Type . STRING ) { serializer = Utf8Serializer . get ( ) ; } else if ( type == Type . BOOLEAN ) { serializer = BooleanSerializer . get ( ) ; } else if ( type == Type . BYTES ) { serializer = ByteBufferSerializer . get ( ) ; } else if ( type == Type . DOUBLE ) { serializer = DoubleSerializer . get ( ) ; } else if ( type == Type . FLOAT ) { serializer = FloatSerializer . get ( ) ; } else if ( type == Type . INT ) { serializer = IntegerSerializer . get ( ) ; } else if ( type == Type . LONG ) { serializer = LongSerializer . get ( ) ; } else if ( type == Type . FIXED ) { Class clazz = TypeUtils . getClass ( schema ) ; serializer = SpecificFixedSerializer . get ( clazz ) ; } else if ( type == Type . ARRAY ) { serializer = GenericArraySerializer . get ( schema . getElementType ( ) ) ; } else if ( type == Type . MAP ) { serializer = StatefulHashMapSerializer . get ( schema . getValueType ( ) ) ; } else { serializer = null ; } return serializer ; } @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) public static < T > Serializer < T > getSerializer ( Type type ) { Serializer serializer = null ; if ( type == Type . STRING ) { serializer = Utf8Serializer . get ( ) ; } else if ( type == Type . BOOLEAN ) { serializer = BooleanSerializer . get ( ) ; } else if ( type == Type . BYTES ) { serializer = ByteBufferSerializer . get ( ) ; } else if ( type == Type . DOUBLE ) { serializer = DoubleSerializer . get ( ) ; } else if ( type == Type . FLOAT ) { serializer = FloatSerializer . get ( ) ; } else if ( type == Type . INT ) { serializer = IntegerSerializer . get ( ) ; } else if ( type == Type . LONG ) { serializer = LongSerializer . get ( ) ; } else if ( type == Type . FIXED ) { serializer = SpecificFixedSerializer . get ( ) ; } else { serializer = null ; } return serializer ; } @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) public static < T > Serializer < T > getSerializer ( Type type , Type elementType ) { Serializer serializer = null ; if ( type == null ) { if ( elementType == null ) { serializer = null ; } else { serializer = getSerializer ( elementType ) ; } } else { if ( elementType == null ) { serializer = getSerializer ( type ) ; } } if ( type == Type . ARRAY ) { serializer = GenericArraySerializer . get ( elementType ) ; } else if ( type == Type . MAP ) { serializer = StatefulHashMapSerializer . get ( elementType ) ; } else { serializer = null ; } return serializer ; } @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) public static < T > Serializer < T > getSerializer ( Type type , Class < T > clazz ) { Serializer serializer = null ; if ( type != Type . FIXED ) { serializer = null ; } if ( clazz == null ) { serializer = null ; } else { serializer = SpecificFixedSerializer . get ( clazz ) ; } return serializer ; } } </s>
|
<s> package org . apache . gora . cassandra . serializers ; import java . nio . BufferUnderflowException ; import java . nio . ByteBuffer ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import me . prettyprint . cassandra . serializers . AbstractSerializer ; import me . prettyprint . cassandra . serializers . BytesArraySerializer ; import me . prettyprint . cassandra . serializers . IntegerSerializer ; import me . prettyprint . hector . api . Serializer ; import me . prettyprint . hector . api . ddl . ComparatorType ; import static me . prettyprint . hector . api . ddl . ComparatorType . UTF8TYPE ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Type ; import org . apache . avro . specific . SpecificFixed ; import org . apache . avro . util . Utf8 ; import org . apache . gora . persistency . State ; import org . apache . gora . persistency . StatefulHashMap ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class StatefulHashMapSerializer < T > extends AbstractSerializer < StatefulHashMap < Utf8 , T > > { public static final Logger LOG = LoggerFactory . getLogger ( StatefulHashMapSerializer . class ) ; private static Map < Type , StatefulHashMapSerializer > valueTypeToSerializerMap = new HashMap < Type , StatefulHashMapSerializer > ( ) ; private static Map < Class , StatefulHashMapSerializer > fixedClassToSerializerMap = new HashMap < Class , StatefulHashMapSerializer > ( ) ; public static StatefulHashMapSerializer get ( Type valueType ) { StatefulHashMapSerializer serializer = valueTypeToSerializerMap . get ( valueType ) ; if ( serializer == null ) { serializer = new StatefulHashMapSerializer ( valueType ) ; valueTypeToSerializerMap . put ( valueType , serializer ) ; } return serializer ; } public static StatefulHashMapSerializer get ( Type valueType , Class clazz ) { if ( valueType != Type . FIXED ) { return null ; } StatefulHashMapSerializer serializer = valueTypeToSerializerMap . get ( clazz ) ; if ( serializer == null ) { serializer = new StatefulHashMapSerializer ( clazz ) ; fixedClassToSerializerMap . put ( clazz , serializer ) ; } return serializer ; } public static StatefulHashMapSerializer get ( Schema valueSchema ) { Type type = valueSchema . getType ( ) ; if ( type == Type . FIXED ) { return get ( Type . FIXED , TypeUtils . getClass ( valueSchema ) ) ; } else { return get ( type ) ; } } private Schema valueSchema = null ; private Type valueType = null ; private int size = - <NUM_LIT:1> ; private Class < T > clazz = null ; private Serializer < T > valueSerializer = null ; public StatefulHashMapSerializer ( Serializer < T > valueSerializer ) { this . valueSerializer = valueSerializer ; } public StatefulHashMapSerializer ( Schema valueSchema ) { this . valueSchema = valueSchema ; valueType = valueSchema . getType ( ) ; size = TypeUtils . getFixedSize ( valueSchema ) ; valueSerializer = GoraSerializerTypeInferer . getSerializer ( valueSchema ) ; } public StatefulHashMapSerializer ( Type valueType ) { this . valueType = valueType ; if ( valueType != Type . FIXED ) { valueSchema = Schema . create ( valueType ) ; } clazz = TypeUtils . getClass ( valueType ) ; size = TypeUtils . getFixedSize ( valueType ) ; valueSerializer = GoraSerializerTypeInferer . getSerializer ( valueType ) ; } public StatefulHashMapSerializer ( Class < T > clazz ) { this . clazz = clazz ; valueType = TypeUtils . getType ( clazz ) ; size = TypeUtils . getFixedSize ( clazz ) ; if ( valueType == null || valueType == Type . FIXED ) { valueType = Type . FIXED ; valueSchema = TypeUtils . getSchema ( clazz ) ; valueSerializer = GoraSerializerTypeInferer . getSerializer ( valueType , clazz ) ; } else { valueSerializer = GoraSerializerTypeInferer . getSerializer ( valueType ) ; } } @ Override public ByteBuffer toByteBuffer ( StatefulHashMap < Utf8 , T > map ) { if ( map == null ) { return null ; } if ( size > <NUM_LIT:0> ) { return toByteBufferWithFixedLengthElements ( map ) ; } else { return toByteBufferWithVariableLengthElements ( map ) ; } } private ByteBuffer toByteBufferWithFixedLengthElements ( StatefulHashMap < Utf8 , T > map ) { List < byte [ ] > list = new ArrayList < byte [ ] > ( map . size ( ) ) ; int n = <NUM_LIT:0> ; for ( Utf8 key : map . keySet ( ) ) { if ( map . getState ( key ) == State . DELETED ) { continue ; } T value = map . get ( key ) ; byte [ ] bytes = BytesArraySerializer . get ( ) . fromByteBuffer ( Utf8Serializer . get ( ) . toByteBuffer ( key ) ) ; list . add ( bytes ) ; n += <NUM_LIT:4> ; n += bytes . length ; bytes = BytesArraySerializer . get ( ) . fromByteBuffer ( valueSerializer . toByteBuffer ( value ) ) ; list . add ( bytes ) ; n += bytes . length ; } ByteBuffer byteBuffer = ByteBuffer . allocate ( n ) ; int i = <NUM_LIT:0> ; for ( byte [ ] bytes : list ) { if ( i % <NUM_LIT:2> == <NUM_LIT:0> ) { byteBuffer . put ( IntegerSerializer . get ( ) . toByteBuffer ( bytes . length ) ) ; } byteBuffer . put ( BytesArraySerializer . get ( ) . toByteBuffer ( bytes ) ) ; i += <NUM_LIT:1> ; } byteBuffer . rewind ( ) ; return byteBuffer ; } private ByteBuffer toByteBufferWithVariableLengthElements ( StatefulHashMap < Utf8 , T > map ) { List < byte [ ] > list = new ArrayList < byte [ ] > ( map . size ( ) ) ; int n = <NUM_LIT:0> ; for ( Utf8 key : map . keySet ( ) ) { if ( map . getState ( key ) == State . DELETED ) { continue ; } T value = map . get ( key ) ; byte [ ] bytes = BytesArraySerializer . get ( ) . fromByteBuffer ( Utf8Serializer . get ( ) . toByteBuffer ( key ) ) ; list . add ( bytes ) ; n += <NUM_LIT:4> ; n += bytes . length ; bytes = BytesArraySerializer . get ( ) . fromByteBuffer ( valueSerializer . toByteBuffer ( value ) ) ; list . add ( bytes ) ; n += <NUM_LIT:4> ; n += bytes . length ; } ByteBuffer byteBuffer = ByteBuffer . allocate ( n ) ; for ( byte [ ] bytes : list ) { byteBuffer . put ( IntegerSerializer . get ( ) . toByteBuffer ( bytes . length ) ) ; byteBuffer . put ( BytesArraySerializer . get ( ) . toByteBuffer ( bytes ) ) ; } byteBuffer . rewind ( ) ; return byteBuffer ; } @ Override public StatefulHashMap < Utf8 , T > fromByteBuffer ( ByteBuffer byteBuffer ) { if ( byteBuffer == null ) { return null ; } StatefulHashMap < Utf8 , T > map = new StatefulHashMap < Utf8 , T > ( ) ; int i = <NUM_LIT:0> ; while ( true ) { Utf8 key = null ; T value = null ; try { int n = IntegerSerializer . get ( ) . fromByteBuffer ( byteBuffer ) ; byte [ ] bytes = new byte [ n ] ; byteBuffer . get ( bytes , <NUM_LIT:0> , n ) ; key = Utf8Serializer . get ( ) . fromByteBuffer ( BytesArraySerializer . get ( ) . toByteBuffer ( bytes ) ) ; if ( size > <NUM_LIT:0> ) { value = valueSerializer . fromByteBuffer ( byteBuffer ) ; } else { n = IntegerSerializer . get ( ) . fromByteBuffer ( byteBuffer ) ; bytes = new byte [ n ] ; byteBuffer . get ( bytes , <NUM_LIT:0> , n ) ; value = valueSerializer . fromByteBuffer ( BytesArraySerializer . get ( ) . toByteBuffer ( bytes ) ) ; } } catch ( BufferUnderflowException e ) { break ; } if ( key == null ) { break ; } if ( value == null ) { break ; } map . put ( key , value ) ; } return map ; } @ Override public ComparatorType getComparatorType ( ) { return valueSerializer . getComparatorType ( ) ; } } </s>
|
<s> package org . apache . gora . cassandra . store ; import java . io . IOException ; import org . apache . gora . cassandra . GoraCassandraTestDriver ; import org . apache . gora . cassandra . store . CassandraStore ; import org . apache . gora . examples . generated . Employee ; import org . apache . gora . examples . generated . WebPage ; import org . apache . gora . store . DataStore ; import org . apache . gora . store . DataStoreFactory ; import org . apache . gora . store . DataStoreTestBase ; import org . apache . hadoop . conf . Configuration ; import org . junit . After ; import org . junit . Before ; import org . junit . Test ; public class TestCassandraStore extends DataStoreTestBase { private Configuration conf ; static { setTestDriver ( new GoraCassandraTestDriver ( ) ) ; } @ Before public void setUp ( ) throws Exception { super . setUp ( ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) @ Override protected DataStore < String , Employee > createEmployeeDataStore ( ) throws IOException { return DataStoreFactory . getDataStore ( CassandraStore . class , String . class , Employee . class , conf ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) @ Override protected DataStore < String , WebPage > createWebPageDataStore ( ) throws IOException { return DataStoreFactory . getDataStore ( CassandraStore . class , String . class , WebPage . class , conf ) ; } public GoraCassandraTestDriver getTestDriver ( ) { return ( GoraCassandraTestDriver ) testDriver ; } @ Override public void testGetWebPageDefaultFields ( ) throws IOException { } @ Override public void testQuery ( ) throws IOException { } @ Override public void testQueryStartKey ( ) throws IOException { } @ Override public void testQueryEndKey ( ) throws IOException { } @ Override public void testQueryKeyRange ( ) throws IOException { } @ Override public void testQueryWebPageSingleKeyDefaultFields ( ) throws IOException { } @ Override public void testDelete ( ) throws IOException { } @ Override public void testDeleteByQuery ( ) throws IOException { } @ Override public void testDeleteByQueryFields ( ) throws IOException { } @ Override public void testGetPartitions ( ) throws IOException { } public static void main ( String [ ] args ) throws Exception { TestCassandraStore test = new TestCassandraStore ( ) ; test . setUpClass ( ) ; test . setUp ( ) ; test . tearDown ( ) ; test . tearDownClass ( ) ; } } </s>
|
<s> package org . apache . gora . cassandra ; import java . io . IOException ; import org . apache . gora . GoraTestDriver ; import org . apache . gora . cassandra . store . CassandraStore ; import org . apache . hadoop . conf . Configuration ; import java . io . File ; import org . apache . cassandra . io . util . FileUtils ; import org . apache . cassandra . thrift . CassandraDaemon ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class GoraCassandraTestDriver extends GoraTestDriver { private static Logger log = LoggerFactory . getLogger ( GoraCassandraTestDriver . class ) ; private String baseDirectory = "<STR_LIT>" ; private CassandraDaemon cassandraDaemon ; private Thread cassandraThread ; public String getBaseDirectory ( ) { return baseDirectory ; } public GoraCassandraTestDriver ( ) { super ( CassandraStore . class ) ; } @ Override public void setUpClass ( ) throws Exception { super . setUpClass ( ) ; log . info ( "<STR_LIT>" ) ; try { cleanupDirectoriesFailover ( ) ; FileUtils . createDirectory ( baseDirectory ) ; System . setProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; System . setProperty ( "<STR_LIT>" , "<STR_LIT>" ) ; cassandraDaemon = new CassandraDaemon ( ) ; cassandraDaemon . init ( null ) ; cassandraThread = new Thread ( new Runnable ( ) { public void run ( ) { try { cassandraDaemon . start ( ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" , e ) ; } } } ) ; cassandraThread . setDaemon ( true ) ; cassandraThread . start ( ) ; } catch ( Exception e ) { log . error ( "<STR_LIT>" , e ) ; tearDownClass ( ) ; } } @ Override public void tearDownClass ( ) throws Exception { super . tearDownClass ( ) ; log . info ( "<STR_LIT>" ) ; if ( cassandraThread != null ) { cassandraDaemon . stop ( ) ; cassandraDaemon . destroy ( ) ; cassandraThread . interrupt ( ) ; cassandraThread = null ; } cleanupDirectoriesFailover ( ) ; } public void cleanupDirectoriesFailover ( ) { int tries = <NUM_LIT:3> ; while ( tries -- > <NUM_LIT:0> ) { try { cleanupDirectories ( ) ; break ; } catch ( Exception e ) { try { Thread . sleep ( <NUM_LIT> ) ; } catch ( InterruptedException e1 ) { } } } } public void cleanupDirectories ( ) throws Exception { File dirFile = new File ( baseDirectory ) ; if ( dirFile . exists ( ) ) { FileUtils . deleteRecursive ( dirFile ) ; } } } </s>
|
<s> package org . apache . gora . tutorial . log ; import java . io . IOException ; import org . apache . avro . util . Utf8 ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . apache . gora . mapreduce . GoraMapper ; import org . apache . gora . mapreduce . GoraReducer ; import org . apache . gora . store . DataStore ; import org . apache . gora . store . DataStoreFactory ; import org . apache . gora . tutorial . log . generated . MetricDatum ; import org . apache . gora . tutorial . log . generated . Pageview ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . io . LongWritable ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . mapreduce . Job ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; public class LogAnalytics extends Configured implements Tool { private static final Logger log = LoggerFactory . getLogger ( LogAnalytics . class ) ; private static final long DAY_MILIS = <NUM_LIT:1000> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:24> ; public static class LogAnalyticsMapper extends GoraMapper < Long , Pageview , TextLong , LongWritable > { private LongWritable one = new LongWritable ( <NUM_LIT:1L> ) ; private TextLong tuple ; @ Override protected void setup ( Context context ) throws IOException , InterruptedException { tuple = new TextLong ( ) ; tuple . setKey ( new Text ( ) ) ; tuple . setValue ( new LongWritable ( ) ) ; } ; @ Override protected void map ( Long key , Pageview pageview , Context context ) throws IOException , InterruptedException { Utf8 url = pageview . getUrl ( ) ; long day = getDay ( pageview . getTimestamp ( ) ) ; tuple . getKey ( ) . set ( url . toString ( ) ) ; tuple . getValue ( ) . set ( day ) ; context . write ( tuple , one ) ; } ; private long getDay ( long timeStamp ) { return ( timeStamp / DAY_MILIS ) * DAY_MILIS ; } } public static class LogAnalyticsReducer extends GoraReducer < TextLong , LongWritable , String , MetricDatum > { private MetricDatum metricDatum = new MetricDatum ( ) ; @ Override protected void reduce ( TextLong tuple , Iterable < LongWritable > values , Context context ) throws IOException , InterruptedException { long sum = <NUM_LIT> ; for ( LongWritable value : values ) { sum += value . get ( ) ; } String dimension = tuple . getKey ( ) . toString ( ) ; long timestamp = tuple . getValue ( ) . get ( ) ; metricDatum . setMetricDimension ( new Utf8 ( dimension ) ) ; metricDatum . setTimestamp ( timestamp ) ; String key = metricDatum . getMetricDimension ( ) . toString ( ) ; key += "<STR_LIT:_>" + Long . toString ( timestamp ) ; metricDatum . setMetric ( sum ) ; context . write ( key , metricDatum ) ; } ; } public Job createJob ( DataStore < Long , Pageview > inStore , DataStore < String , MetricDatum > outStore , int numReducer ) throws IOException { Job job = new Job ( getConf ( ) ) ; job . setJobName ( "<STR_LIT>" ) ; job . setNumReduceTasks ( numReducer ) ; job . setJarByClass ( getClass ( ) ) ; GoraMapper . initMapperJob ( job , inStore , TextLong . class , LongWritable . class , LogAnalyticsMapper . class , true ) ; GoraReducer . initReducerJob ( job , outStore , LogAnalyticsReducer . class ) ; return job ; } @ Override public int run ( String [ ] args ) throws Exception { DataStore < Long , Pageview > inStore ; DataStore < String , MetricDatum > outStore ; Configuration conf = new Configuration ( ) ; if ( args . length > <NUM_LIT:0> ) { String dataStoreClass = args [ <NUM_LIT:0> ] ; inStore = DataStoreFactory . getDataStore ( dataStoreClass , Long . class , Pageview . class , conf ) ; if ( args . length > <NUM_LIT:1> ) { dataStoreClass = args [ <NUM_LIT:1> ] ; } outStore = DataStoreFactory . getDataStore ( dataStoreClass , String . class , MetricDatum . class , conf ) ; } else { inStore = DataStoreFactory . getDataStore ( Long . class , Pageview . class , conf ) ; outStore = DataStoreFactory . getDataStore ( String . class , MetricDatum . class , conf ) ; } Job job = createJob ( inStore , outStore , <NUM_LIT:3> ) ; boolean success = job . waitForCompletion ( true ) ; inStore . close ( ) ; outStore . close ( ) ; log . info ( "<STR_LIT>" + ( success ? "<STR_LIT:success>" : "<STR_LIT>" ) ) ; return success ? <NUM_LIT:0> : <NUM_LIT:1> ; } private static final String USAGE = "<STR_LIT>" ; public static void main ( String [ ] args ) throws Exception { if ( args . length < <NUM_LIT:2> ) { System . err . println ( USAGE ) ; System . exit ( <NUM_LIT:1> ) ; } int ret = ToolRunner . run ( new LogAnalytics ( ) , args ) ; System . exit ( ret ) ; } } </s>
|
<s> package org . apache . gora . tutorial . log ; import org . apache . hadoop . io . LongWritable ; import org . apache . hadoop . io . Text ; public class TextLong extends KeyValueWritable < Text , LongWritable > { public TextLong ( ) { key = new Text ( ) ; value = new LongWritable ( ) ; } } </s>
|
<s> package org . apache . gora . tutorial . log ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . WritableComparable ; public class KeyValueWritable < K extends WritableComparable , V extends WritableComparable > implements WritableComparable < KeyValueWritable < K , V > > { protected K key = null ; protected V value = null ; public KeyValueWritable ( ) { } public KeyValueWritable ( K key , V value ) { this . key = key ; this . value = value ; } public K getKey ( ) { return key ; } public void setKey ( K key ) { this . key = key ; } public V getValue ( ) { return value ; } public void setValue ( V value ) { this . value = value ; } @ Override public void readFields ( DataInput in ) throws IOException { if ( key == null ) { } key . readFields ( in ) ; value . readFields ( in ) ; } @ Override public void write ( DataOutput out ) throws IOException { key . write ( out ) ; value . write ( out ) ; } @ Override public int hashCode ( ) { final int prime = <NUM_LIT:31> ; int result = <NUM_LIT:1> ; result = prime * result + ( ( key == null ) ? <NUM_LIT:0> : key . hashCode ( ) ) ; result = prime * result + ( ( value == null ) ? <NUM_LIT:0> : value . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; KeyValueWritable other = ( KeyValueWritable ) obj ; if ( key == null ) { if ( other . key != null ) return false ; } else if ( ! key . equals ( other . key ) ) return false ; if ( value == null ) { if ( other . value != null ) return false ; } else if ( ! value . equals ( other . value ) ) return false ; return true ; } @ Override public int compareTo ( KeyValueWritable < K , V > o ) { int cmp = key . compareTo ( o . key ) ; if ( cmp != <NUM_LIT:0> ) return cmp ; return value . compareTo ( o . value ) ; } } </s>
|
<s> package org . apache . gora . tutorial . log ; import java . io . BufferedReader ; import java . io . FileReader ; import java . io . IOException ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . StringTokenizer ; import org . apache . avro . util . Utf8 ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . apache . gora . query . Query ; import org . apache . gora . query . Result ; import org . apache . gora . store . DataStore ; import org . apache . gora . store . DataStoreFactory ; import org . apache . gora . tutorial . log . generated . Pageview ; import org . apache . hadoop . conf . Configuration ; public class LogManager { private static final Logger log = LoggerFactory . getLogger ( LogManager . class ) ; private DataStore < Long , Pageview > dataStore ; private static final SimpleDateFormat dateFormat = new SimpleDateFormat ( "<STR_LIT>" ) ; public LogManager ( ) { try { init ( ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } } private void init ( ) throws IOException { dataStore = DataStoreFactory . getDataStore ( Long . class , Pageview . class , new Configuration ( ) ) ; } private void parse ( String input ) throws IOException , ParseException { log . info ( "<STR_LIT>" + input ) ; BufferedReader reader = new BufferedReader ( new FileReader ( input ) ) ; long lineCount = <NUM_LIT:0> ; try { String line = reader . readLine ( ) ; do { Pageview pageview = parseLine ( line ) ; if ( pageview != null ) { storePageview ( lineCount ++ , pageview ) ; } line = reader . readLine ( ) ; } while ( line != null ) ; } finally { reader . close ( ) ; } log . info ( "<STR_LIT>" + lineCount ) ; } private Pageview parseLine ( String line ) throws ParseException { StringTokenizer matcher = new StringTokenizer ( line ) ; String ip = matcher . nextToken ( ) ; matcher . nextToken ( ) ; matcher . nextToken ( ) ; long timestamp = dateFormat . parse ( matcher . nextToken ( "<STR_LIT:]>" ) . substring ( <NUM_LIT:2> ) ) . getTime ( ) ; matcher . nextToken ( "<STR_LIT:\">" ) ; String request = matcher . nextToken ( "<STR_LIT:\">" ) ; String [ ] requestParts = request . split ( "<STR_LIT:U+0020>" ) ; String httpMethod = requestParts [ <NUM_LIT:0> ] ; String url = requestParts [ <NUM_LIT:1> ] ; matcher . nextToken ( "<STR_LIT:U+0020>" ) ; int httpStatusCode = Integer . parseInt ( matcher . nextToken ( ) ) ; int responseSize = Integer . parseInt ( matcher . nextToken ( ) ) ; matcher . nextToken ( "<STR_LIT:\">" ) ; String referrer = matcher . nextToken ( "<STR_LIT:\">" ) ; matcher . nextToken ( "<STR_LIT:\">" ) ; String userAgent = matcher . nextToken ( "<STR_LIT:\">" ) ; Pageview pageview = new Pageview ( ) ; pageview . setIp ( new Utf8 ( ip ) ) ; pageview . setTimestamp ( timestamp ) ; pageview . setHttpMethod ( new Utf8 ( httpMethod ) ) ; pageview . setUrl ( new Utf8 ( url ) ) ; pageview . setHttpStatusCode ( httpStatusCode ) ; pageview . setResponseSize ( responseSize ) ; pageview . setReferrer ( new Utf8 ( referrer ) ) ; pageview . setUserAgent ( new Utf8 ( userAgent ) ) ; return pageview ; } private void storePageview ( long key , Pageview pageview ) throws IOException { log . info ( "<STR_LIT>" + dataStore . toString ( ) ) ; dataStore . put ( key , pageview ) ; } private void get ( long key ) throws IOException { Pageview pageview = dataStore . get ( key ) ; printPageview ( pageview ) ; } private void query ( long key ) throws IOException { Query < Long , Pageview > query = dataStore . newQuery ( ) ; query . setKey ( key ) ; Result < Long , Pageview > result = query . execute ( ) ; printResult ( result ) ; } private void query ( long startKey , long endKey ) throws IOException { Query < Long , Pageview > query = dataStore . newQuery ( ) ; query . setStartKey ( startKey ) ; query . setEndKey ( endKey ) ; Result < Long , Pageview > result = query . execute ( ) ; printResult ( result ) ; } private void delete ( long lineNum ) throws Exception { dataStore . delete ( lineNum ) ; dataStore . flush ( ) ; log . info ( "<STR_LIT>" + lineNum + "<STR_LIT>" ) ; } private void deleteByQuery ( long startKey , long endKey ) throws IOException { Query < Long , Pageview > query = dataStore . newQuery ( ) ; query . setStartKey ( startKey ) ; query . setEndKey ( endKey ) ; dataStore . deleteByQuery ( query ) ; log . info ( "<STR_LIT>" + startKey + "<STR_LIT:U+0020andU+0020>" + endKey + "<STR_LIT>" ) ; } private void printResult ( Result < Long , Pageview > result ) throws IOException { while ( result . next ( ) ) { long resultKey = result . getKey ( ) ; Pageview resultPageview = result . get ( ) ; System . out . println ( resultKey + "<STR_LIT::>" ) ; printPageview ( resultPageview ) ; } System . out . println ( "<STR_LIT>" + result . getOffset ( ) ) ; } private void printPageview ( Pageview pageview ) { if ( pageview == null ) { System . out . println ( "<STR_LIT>" ) ; } else { System . out . println ( pageview . toString ( ) ) ; } } private void close ( ) throws IOException { if ( dataStore != null ) dataStore . close ( ) ; } private static final String USAGE = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; public static void main ( String [ ] args ) throws Exception { if ( args . length < <NUM_LIT:2> ) { System . err . println ( USAGE ) ; System . exit ( <NUM_LIT:1> ) ; } LogManager manager = new LogManager ( ) ; if ( "<STR_LIT>" . equals ( args [ <NUM_LIT:0> ] ) ) { manager . parse ( args [ <NUM_LIT:1> ] ) ; } else if ( "<STR_LIT>" . equals ( args [ <NUM_LIT:0> ] ) ) { manager . get ( Long . parseLong ( args [ <NUM_LIT:1> ] ) ) ; } else if ( "<STR_LIT>" . equals ( args [ <NUM_LIT:0> ] ) ) { if ( args . length == <NUM_LIT:2> ) manager . query ( Long . parseLong ( args [ <NUM_LIT:1> ] ) ) ; else manager . query ( Long . parseLong ( args [ <NUM_LIT:1> ] ) , Long . parseLong ( args [ <NUM_LIT:2> ] ) ) ; } else if ( "<STR_LIT>" . equals ( args [ <NUM_LIT:0> ] ) ) { manager . delete ( Long . parseLong ( args [ <NUM_LIT:1> ] ) ) ; } else if ( "<STR_LIT>" . equalsIgnoreCase ( args [ <NUM_LIT:0> ] ) ) { manager . deleteByQuery ( Long . parseLong ( args [ <NUM_LIT:1> ] ) , Long . parseLong ( args [ <NUM_LIT:2> ] ) ) ; } else { System . err . println ( USAGE ) ; System . exit ( <NUM_LIT:1> ) ; } manager . close ( ) ; } } </s>
|
<s> package org . apache . gora . tutorial . log . generated ; import org . apache . avro . AvroRuntimeException ; import org . apache . avro . Schema ; import org . apache . avro . util . Utf8 ; import org . apache . gora . persistency . StateManager ; import org . apache . gora . persistency . impl . PersistentBase ; import org . apache . gora . persistency . impl . StateManagerImpl ; @ SuppressWarnings ( "<STR_LIT:all>" ) public class MetricDatum extends PersistentBase { public static final Schema _SCHEMA = Schema . parse ( "<STR_LIT>" ) ; public static enum Field { METRIC_DIMENSION ( <NUM_LIT:0> , "<STR_LIT>" ) , TIMESTAMP ( <NUM_LIT:1> , "<STR_LIT>" ) , METRIC ( <NUM_LIT:2> , "<STR_LIT>" ) , ; private int index ; private String name ; Field ( int index , String name ) { this . index = index ; this . name = name ; } public int getIndex ( ) { return index ; } public String getName ( ) { return name ; } public String toString ( ) { return name ; } } ; public static final String [ ] _ALL_FIELDS = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , } ; static { PersistentBase . registerFields ( MetricDatum . class , _ALL_FIELDS ) ; } private Utf8 metricDimension ; private long timestamp ; private long metric ; public MetricDatum ( ) { this ( new StateManagerImpl ( ) ) ; } public MetricDatum ( StateManager stateManager ) { super ( stateManager ) ; } public MetricDatum newInstance ( StateManager stateManager ) { return new MetricDatum ( stateManager ) ; } public Schema getSchema ( ) { return _SCHEMA ; } public Object get ( int _field ) { switch ( _field ) { case <NUM_LIT:0> : return metricDimension ; case <NUM_LIT:1> : return timestamp ; case <NUM_LIT:2> : return metric ; default : throw new AvroRuntimeException ( "<STR_LIT>" ) ; } } @ SuppressWarnings ( value = "<STR_LIT:unchecked>" ) public void put ( int _field , Object _value ) { if ( isFieldEqual ( _field , _value ) ) return ; getStateManager ( ) . setDirty ( this , _field ) ; switch ( _field ) { case <NUM_LIT:0> : metricDimension = ( Utf8 ) _value ; break ; case <NUM_LIT:1> : timestamp = ( Long ) _value ; break ; case <NUM_LIT:2> : metric = ( Long ) _value ; break ; default : throw new AvroRuntimeException ( "<STR_LIT>" ) ; } } public Utf8 getMetricDimension ( ) { return ( Utf8 ) get ( <NUM_LIT:0> ) ; } public void setMetricDimension ( Utf8 value ) { put ( <NUM_LIT:0> , value ) ; } public long getTimestamp ( ) { return ( Long ) get ( <NUM_LIT:1> ) ; } public void setTimestamp ( long value ) { put ( <NUM_LIT:1> , value ) ; } public long getMetric ( ) { return ( Long ) get ( <NUM_LIT:2> ) ; } public void setMetric ( long value ) { put ( <NUM_LIT:2> , value ) ; } } </s>
|
<s> package org . apache . gora . tutorial . log . generated ; import org . apache . avro . AvroRuntimeException ; import org . apache . avro . Schema ; import org . apache . avro . util . Utf8 ; import org . apache . gora . persistency . StateManager ; import org . apache . gora . persistency . impl . PersistentBase ; import org . apache . gora . persistency . impl . StateManagerImpl ; @ SuppressWarnings ( "<STR_LIT:all>" ) public class Pageview extends PersistentBase { public static final Schema _SCHEMA = Schema . parse ( "<STR_LIT>" ) ; public static enum Field { URL ( <NUM_LIT:0> , "<STR_LIT:url>" ) , TIMESTAMP ( <NUM_LIT:1> , "<STR_LIT>" ) , IP ( <NUM_LIT:2> , "<STR_LIT>" ) , HTTP_METHOD ( <NUM_LIT:3> , "<STR_LIT>" ) , HTTP_STATUS_CODE ( <NUM_LIT:4> , "<STR_LIT>" ) , RESPONSE_SIZE ( <NUM_LIT:5> , "<STR_LIT>" ) , REFERRER ( <NUM_LIT:6> , "<STR_LIT>" ) , USER_AGENT ( <NUM_LIT:7> , "<STR_LIT>" ) , ; private int index ; private String name ; Field ( int index , String name ) { this . index = index ; this . name = name ; } public int getIndex ( ) { return index ; } public String getName ( ) { return name ; } public String toString ( ) { return name ; } } ; public static final String [ ] _ALL_FIELDS = { "<STR_LIT:url>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , } ; static { PersistentBase . registerFields ( Pageview . class , _ALL_FIELDS ) ; } private Utf8 url ; private long timestamp ; private Utf8 ip ; private Utf8 httpMethod ; private int httpStatusCode ; private int responseSize ; private Utf8 referrer ; private Utf8 userAgent ; public Pageview ( ) { this ( new StateManagerImpl ( ) ) ; } public Pageview ( StateManager stateManager ) { super ( stateManager ) ; } public Pageview newInstance ( StateManager stateManager ) { return new Pageview ( stateManager ) ; } public Schema getSchema ( ) { return _SCHEMA ; } public Object get ( int _field ) { switch ( _field ) { case <NUM_LIT:0> : return url ; case <NUM_LIT:1> : return timestamp ; case <NUM_LIT:2> : return ip ; case <NUM_LIT:3> : return httpMethod ; case <NUM_LIT:4> : return httpStatusCode ; case <NUM_LIT:5> : return responseSize ; case <NUM_LIT:6> : return referrer ; case <NUM_LIT:7> : return userAgent ; default : throw new AvroRuntimeException ( "<STR_LIT>" ) ; } } @ SuppressWarnings ( value = "<STR_LIT:unchecked>" ) public void put ( int _field , Object _value ) { if ( isFieldEqual ( _field , _value ) ) return ; getStateManager ( ) . setDirty ( this , _field ) ; switch ( _field ) { case <NUM_LIT:0> : url = ( Utf8 ) _value ; break ; case <NUM_LIT:1> : timestamp = ( Long ) _value ; break ; case <NUM_LIT:2> : ip = ( Utf8 ) _value ; break ; case <NUM_LIT:3> : httpMethod = ( Utf8 ) _value ; break ; case <NUM_LIT:4> : httpStatusCode = ( Integer ) _value ; break ; case <NUM_LIT:5> : responseSize = ( Integer ) _value ; break ; case <NUM_LIT:6> : referrer = ( Utf8 ) _value ; break ; case <NUM_LIT:7> : userAgent = ( Utf8 ) _value ; break ; default : throw new AvroRuntimeException ( "<STR_LIT>" ) ; } } public Utf8 getUrl ( ) { return ( Utf8 ) get ( <NUM_LIT:0> ) ; } public void setUrl ( Utf8 value ) { put ( <NUM_LIT:0> , value ) ; } public long getTimestamp ( ) { return ( Long ) get ( <NUM_LIT:1> ) ; } public void setTimestamp ( long value ) { put ( <NUM_LIT:1> , value ) ; } public Utf8 getIp ( ) { return ( Utf8 ) get ( <NUM_LIT:2> ) ; } public void setIp ( Utf8 value ) { put ( <NUM_LIT:2> , value ) ; } public Utf8 getHttpMethod ( ) { return ( Utf8 ) get ( <NUM_LIT:3> ) ; } public void setHttpMethod ( Utf8 value ) { put ( <NUM_LIT:3> , value ) ; } public int getHttpStatusCode ( ) { return ( Integer ) get ( <NUM_LIT:4> ) ; } public void setHttpStatusCode ( int value ) { put ( <NUM_LIT:4> , value ) ; } public int getResponseSize ( ) { return ( Integer ) get ( <NUM_LIT:5> ) ; } public void setResponseSize ( int value ) { put ( <NUM_LIT:5> , value ) ; } public Utf8 getReferrer ( ) { return ( Utf8 ) get ( <NUM_LIT:6> ) ; } public void setReferrer ( Utf8 value ) { put ( <NUM_LIT:6> , value ) ; } public Utf8 getUserAgent ( ) { return ( Utf8 ) get ( <NUM_LIT:7> ) ; } public void setUserAgent ( Utf8 value ) { put ( <NUM_LIT:7> , value ) ; } } </s>
|
<s> package org . apache . gora . sql . store ; import java . io . IOException ; import org . apache . gora . examples . generated . Employee ; import org . apache . gora . examples . generated . WebPage ; import org . apache . gora . sql . GoraSqlTestDriver ; import org . apache . gora . sql . store . SqlStore ; import org . apache . gora . store . DataStore ; import org . apache . gora . store . DataStoreFactory ; import org . apache . gora . store . DataStoreTestBase ; public class TestSqlStore extends DataStoreTestBase { static { setTestDriver ( new GoraSqlTestDriver ( ) ) ; } public TestSqlStore ( ) { } @ Override protected DataStore < String , Employee > createEmployeeDataStore ( ) throws IOException { SqlStore < String , Employee > store = new SqlStore < String , Employee > ( ) ; store . initialize ( String . class , Employee . class , DataStoreFactory . properties ) ; return store ; } @ Override protected DataStore < String , WebPage > createWebPageDataStore ( ) throws IOException { SqlStore < String , WebPage > store = new SqlStore < String , WebPage > ( ) ; store . initialize ( String . class , WebPage . class , DataStoreFactory . properties ) ; return store ; } public void testDeleteByQueryFields ( ) { } public void testDeleteByQuery ( ) throws IOException { } public void testGet ( ) { } public void testSchemaExists ( ) { } public void testGetWithFields ( ) { } public void testGetWebPage ( ) { } public void testGetWebPageDefaultFields ( ) { } public void testDelete ( ) { } public void testGetPartitions ( ) { } public void testTruncateSchema ( ) { } public void testDeleteSchema ( ) { } public void testPutNested ( ) { } public void testUpdate ( ) { } public void testQuery ( ) { } public void testQueryStartKey ( ) { } public void testQueryEndKey ( ) { } public void testQueryKeyRange ( ) { } public void testQueryWebPageSingleKey ( ) { } public void testQueryWebPageSingleKeyDefaultFields ( ) { } public void testQueryWebPageQueryEmptyResults ( ) { } public static void main ( String [ ] args ) throws Exception { TestSqlStore test = new TestSqlStore ( ) ; TestSqlStore . setUpClass ( ) ; test . setUp ( ) ; test . testDeleteByQuery ( ) ; test . tearDown ( ) ; TestSqlStore . tearDownClass ( ) ; } } </s>
|
<s> package org . apache . gora . sql ; import java . sql . Connection ; import java . sql . DriverManager ; import java . util . Properties ; import org . apache . gora . GoraTestDriver ; import org . apache . gora . sql . store . SqlStore ; import org . apache . gora . util . ClassLoadingUtils ; import org . apache . hadoop . util . StringUtils ; import org . hsqldb . Server ; public class GoraSqlTestDriver extends GoraTestDriver { public GoraSqlTestDriver ( ) { super ( SqlStore . class ) ; } protected static final String DRIVER_CLASS_PROPERTY = "<STR_LIT>" ; protected static final String URL_PROPERTY = "<STR_LIT>" ; protected static final String USERNAME_PROPERTY = "<STR_LIT>" ; protected static final String PASSWORD_PROPERTY = "<STR_LIT>" ; private static final String HSQLDB_PORT = System . getProperty ( "<STR_LIT>" ) != null ? System . getProperty ( "<STR_LIT>" ) : "<STR_LIT>" ; private static final String JDBC_URL = String . format ( "<STR_LIT>" , HSQLDB_PORT ) ; private static final String JDBC_DRIVER_CLASS = "<STR_LIT>" ; private Server server ; private boolean initialized = false ; private boolean startHsqldb = true ; private void startHsqldbServer ( ) { log . info ( "<STR_LIT>" ) ; server = new Server ( ) ; server . setDatabasePath ( <NUM_LIT:0> , System . getProperty ( "<STR_LIT>" , "<STR_LIT>" ) + "<STR_LIT>" ) ; server . setDatabaseName ( <NUM_LIT:0> , "<STR_LIT>" ) ; server . setDaemon ( true ) ; server . setPort ( Integer . parseInt ( HSQLDB_PORT ) ) ; server . start ( ) ; } @ Override public void setUpClass ( ) throws Exception { super . setUpClass ( ) ; if ( ! this . initialized && startHsqldb ) { startHsqldbServer ( ) ; this . initialized = true ; } } @ Override public void tearDownClass ( ) throws Exception { super . tearDownClass ( ) ; try { if ( server != null ) { server . shutdown ( ) ; } } catch ( Throwable ex ) { log . warn ( "<STR_LIT>" + StringUtils . stringifyException ( ex ) ) ; } } @ Override public void tearDown ( ) throws Exception { super . tearDown ( ) ; } @ SuppressWarnings ( "<STR_LIT:unused>" ) private Connection createConnection ( String driverClassName , String url ) throws Exception { ClassLoadingUtils . loadClass ( driverClassName ) ; Connection connection = DriverManager . getConnection ( url ) ; connection . setAutoCommit ( false ) ; return connection ; } @ Override protected void setProperties ( Properties properties ) { super . setProperties ( properties ) ; properties . setProperty ( "<STR_LIT>" + DRIVER_CLASS_PROPERTY , JDBC_DRIVER_CLASS ) ; properties . setProperty ( "<STR_LIT>" + URL_PROPERTY , JDBC_URL ) ; properties . remove ( "<STR_LIT>" + USERNAME_PROPERTY ) ; properties . remove ( "<STR_LIT>" + PASSWORD_PROPERTY ) ; } } </s>
|
<s> package org . apache . gora . sql . query ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . query . impl . QueryBase ; import org . apache . gora . sql . store . SqlStore ; public class SqlQuery < K , T extends Persistent > extends QueryBase < K , T > { public SqlQuery ( ) { super ( null ) ; } public SqlQuery ( SqlStore < K , T > dataStore ) { super ( dataStore ) ; } } </s>
|
<s> package org . apache . gora . sql . query ; import java . io . IOException ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . query . Query ; import org . apache . gora . query . impl . ResultBase ; import org . apache . gora . sql . store . SqlStore ; import org . apache . gora . sql . util . SqlUtils ; import org . apache . gora . store . DataStore ; public class SqlResult < K , T extends Persistent > extends ResultBase < K , T > { private ResultSet resultSet ; private PreparedStatement statement ; public SqlResult ( DataStore < K , T > dataStore , Query < K , T > query , ResultSet resultSet , PreparedStatement statement ) { super ( dataStore , query ) ; this . resultSet = resultSet ; this . statement = statement ; } @ Override protected boolean nextInner ( ) throws IOException { try { if ( ! resultSet . next ( ) ) { close ( ) ; return false ; } SqlStore < K , T > sqlStore = ( ( SqlStore < K , T > ) dataStore ) ; key = sqlStore . readPrimaryKey ( resultSet ) ; persistent = sqlStore . readObject ( resultSet , persistent , query . getFields ( ) ) ; return true ; } catch ( Exception ex ) { throw new IOException ( ex ) ; } } @ Override public void close ( ) throws IOException { SqlUtils . close ( resultSet ) ; SqlUtils . close ( statement ) ; } @ Override public float getProgress ( ) throws IOException { return <NUM_LIT:0> ; } } </s>
|
<s> package org . apache . gora . sql . util ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . sql . Statement ; public class SqlUtils { public static void close ( ResultSet rs ) { if ( rs != null ) { try { rs . close ( ) ; } catch ( SQLException ignore ) { } } } public static void close ( Statement statement ) { if ( statement != null ) { try { statement . close ( ) ; } catch ( SQLException ignore ) { } } } } </s>
|
<s> package org . apache . gora . sql . store ; import org . apache . gora . sql . store . SqlTypeInterface . JdbcType ; public class Column { public static enum MappingStrategy { SERIALIZED , JOIN_TABLE , SECONDARY_TABLE , } private String tableName ; private String name ; private JdbcType jdbcType ; private String sqlType ; private boolean isPrimaryKey ; private int length = - <NUM_LIT:1> ; private int scale = - <NUM_LIT:1> ; private MappingStrategy mappingStrategy ; public Column ( ) { } public Column ( String name ) { this . name = name ; } public Column ( String name , boolean isPrimaryKey , JdbcType jdbcType , String sqlType , int length , int scale ) { this . name = name ; this . isPrimaryKey = isPrimaryKey ; this . jdbcType = jdbcType ; this . length = length ; this . scale = scale ; this . mappingStrategy = MappingStrategy . SERIALIZED ; this . sqlType = sqlType == null ? jdbcType . getSqlType ( ) : sqlType ; } public Column ( String name , boolean isPrimaryKey , JdbcType jdbcType , int length , int scale ) { this ( name , isPrimaryKey , jdbcType , null , length , scale ) ; } public Column ( String name , boolean isPrimaryKey ) { this . name = name ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } public JdbcType getJdbcType ( ) { return jdbcType ; } public void setJdbcType ( JdbcType jdbcType ) { this . jdbcType = jdbcType ; } public String getSqlType ( ) { return sqlType ; } public void setSqlType ( String sqlType ) { this . sqlType = sqlType ; } public void setLength ( int length ) { this . length = length ; } public int getLength ( ) { return length ; } public int getScale ( ) { return scale ; } public void setScale ( int scale ) { this . scale = scale ; } public int getScaleOrLength ( ) { return length > <NUM_LIT:0> ? length : scale ; } public String getTableName ( ) { return tableName ; } public void setTableName ( String tableName ) { this . tableName = tableName ; } public MappingStrategy getMappingStrategy ( ) { return mappingStrategy ; } public void setMappingStrategy ( MappingStrategy mappingStrategy ) { this . mappingStrategy = mappingStrategy ; } public boolean isPrimaryKey ( ) { return isPrimaryKey ; } } </s>
|
<s> package org . apache . gora . sql . store ; import java . io . IOException ; import java . io . Serializable ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . sql . Types ; import java . util . Currency ; import java . util . HashMap ; import java . util . Locale ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Type ; import org . apache . avro . util . Utf8 ; import org . apache . hadoop . io . DoubleWritable ; import org . apache . hadoop . io . FloatWritable ; import org . apache . hadoop . io . IntWritable ; import org . apache . hadoop . io . LongWritable ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . VIntWritable ; import org . apache . hadoop . io . VLongWritable ; import org . apache . hadoop . io . Writable ; public class SqlTypeInterface { public static enum JdbcType { ARRAY ( Types . ARRAY ) , BIT ( Types . BIT ) , BIGINT ( Types . BIGINT ) , BINARY ( Types . BINARY ) , BLOB ( Types . BLOB ) , BOOLEAN ( Types . BOOLEAN ) , CHAR ( Types . CHAR ) , CLOB ( Types . CLOB ) , DATALINK ( Types . DATALINK ) , DATE ( Types . DATE ) , DECIMAL ( Types . DECIMAL ) , DISTINCT ( Types . DISTINCT ) , DOUBLE ( Types . DOUBLE ) , FLOAT ( Types . FLOAT ) , INTEGER ( Types . INTEGER ) , LONGNVARCHAR ( Types . LONGNVARCHAR ) , LONGVARBINARY ( Types . LONGVARBINARY ) , LONGVARCHAR ( Types . LONGVARCHAR ) , NCHAR ( Types . NCHAR ) , NCLOB ( Types . NCLOB ) , NULL ( Types . NULL ) , NUMERIC ( Types . NUMERIC ) , NVARCHAR ( Types . NVARCHAR ) , OTHER ( Types . OTHER ) , REAL ( Types . REAL ) , REF ( Types . REF ) , ROWID ( Types . ROWID ) , SMALLINT ( Types . SMALLINT ) , SQLXML ( Types . SQLXML , "<STR_LIT>" ) , STRUCT ( Types . STRUCT ) , TIME ( Types . TIME ) , TIMESTAMP ( Types . TIMESTAMP ) , TINYINT ( Types . TINYINT ) , VARBINARY ( Types . VARBINARY ) , VARCHAR ( Types . VARCHAR ) ; private int order ; private String sqlType ; private JdbcType ( int order ) { this . order = order ; } private JdbcType ( int order , String sqlType ) { this . order = order ; this . sqlType = sqlType ; } public String getSqlType ( ) { return sqlType == null ? toString ( ) : sqlType ; } public int getOrder ( ) { return order ; } private static HashMap < Integer , JdbcType > map = new HashMap < Integer , JdbcType > ( ) ; static { for ( JdbcType type : JdbcType . values ( ) ) { map . put ( type . order , type ) ; } } public static final JdbcType get ( int order ) { return map . get ( order ) ; } } ; public static int getSqlType ( Class < ? > clazz ) { if ( Boolean . class . isAssignableFrom ( clazz ) ) { return Types . BIT ; } else if ( Character . class . isAssignableFrom ( clazz ) ) { return Types . CHAR ; } else if ( Byte . class . isAssignableFrom ( clazz ) ) { return Types . TINYINT ; } else if ( Short . class . isAssignableFrom ( clazz ) ) { return Types . SMALLINT ; } else if ( Integer . class . isAssignableFrom ( clazz ) ) { return Types . INTEGER ; } else if ( Long . class . isAssignableFrom ( clazz ) ) { return Types . BIGINT ; } else if ( Float . class . isAssignableFrom ( clazz ) ) { return Types . FLOAT ; } else if ( Double . class . isAssignableFrom ( clazz ) ) { return Types . DOUBLE ; } else if ( java . util . Date . class . isAssignableFrom ( clazz ) ) { return Types . TIMESTAMP ; } else if ( java . sql . Date . class . isAssignableFrom ( clazz ) ) { return Types . DATE ; } else if ( java . sql . Time . class . isAssignableFrom ( clazz ) ) { return Types . TIME ; } else if ( java . sql . Timestamp . class . isAssignableFrom ( clazz ) ) { return Types . TIMESTAMP ; } else if ( String . class . isAssignableFrom ( clazz ) ) { return Types . VARCHAR ; } else if ( Locale . class . isAssignableFrom ( clazz ) ) { return Types . VARCHAR ; } else if ( Currency . class . isAssignableFrom ( clazz ) ) { return Types . VARCHAR ; } else if ( BigInteger . class . isAssignableFrom ( clazz ) ) { return Types . NUMERIC ; } else if ( BigDecimal . class . isAssignableFrom ( clazz ) ) { return Types . DECIMAL ; } else if ( Serializable . class . isAssignableFrom ( clazz ) ) { return Types . LONGVARBINARY ; } else if ( DoubleWritable . class . isAssignableFrom ( clazz ) ) { return Types . DOUBLE ; } else if ( FloatWritable . class . isAssignableFrom ( clazz ) ) { return Types . FLOAT ; } else if ( IntWritable . class . isAssignableFrom ( clazz ) ) { return Types . INTEGER ; } else if ( LongWritable . class . isAssignableFrom ( clazz ) ) { return Types . BIGINT ; } else if ( Text . class . isAssignableFrom ( clazz ) ) { return Types . VARCHAR ; } else if ( VIntWritable . class . isAssignableFrom ( clazz ) ) { return Types . INTEGER ; } else if ( VLongWritable . class . isAssignableFrom ( clazz ) ) { return Types . BIGINT ; } else if ( Writable . class . isAssignableFrom ( clazz ) ) { return Types . LONGVARBINARY ; } else if ( Utf8 . class . isAssignableFrom ( clazz ) ) { return Types . VARCHAR ; } return Types . OTHER ; } public static JdbcType getJdbcType ( Schema schema , int length , int scale ) throws IOException { Type type = schema . getType ( ) ; switch ( type ) { case MAP : return JdbcType . BLOB ; case ARRAY : return JdbcType . BLOB ; case BOOLEAN : return JdbcType . BIT ; case BYTES : return JdbcType . BLOB ; case DOUBLE : return JdbcType . DOUBLE ; case ENUM : return JdbcType . VARCHAR ; case FIXED : return JdbcType . BINARY ; case FLOAT : return JdbcType . FLOAT ; case INT : return JdbcType . INTEGER ; case LONG : return JdbcType . BIGINT ; case NULL : break ; case RECORD : return JdbcType . BLOB ; case STRING : return JdbcType . VARCHAR ; case UNION : throw new IOException ( "<STR_LIT>" ) ; } return null ; } public static JdbcType getJdbcType ( Class < ? > clazz , int length , int scale ) throws IOException { if ( clazz . equals ( Enum . class ) ) { return JdbcType . VARCHAR ; } else if ( clazz . equals ( Byte . TYPE ) || clazz . equals ( Byte . class ) ) { return JdbcType . BLOB ; } else if ( clazz . equals ( Boolean . TYPE ) || clazz . equals ( Boolean . class ) ) { return JdbcType . BIT ; } else if ( clazz . equals ( Short . TYPE ) || clazz . equals ( Short . class ) ) { return JdbcType . INTEGER ; } else if ( clazz . equals ( Integer . TYPE ) || clazz . equals ( Integer . class ) ) { return JdbcType . INTEGER ; } else if ( clazz . equals ( Long . TYPE ) || clazz . equals ( Long . class ) ) { return JdbcType . BIGINT ; } else if ( clazz . equals ( Float . TYPE ) || clazz . equals ( Float . class ) ) { return JdbcType . FLOAT ; } else if ( clazz . equals ( Double . TYPE ) || clazz . equals ( Double . class ) ) { return JdbcType . FLOAT ; } else if ( clazz . equals ( String . class ) ) { return JdbcType . VARCHAR ; } throw new RuntimeException ( "<STR_LIT>" + clazz ) ; } public static JdbcType stringToJdbcType ( String type ) { try { return JdbcType . valueOf ( type ) ; } catch ( IllegalArgumentException ex ) { return JdbcType . OTHER ; } } } </s>
|
<s> package org . apache . gora . sql . store ; import java . util . HashMap ; import org . apache . gora . sql . store . SqlTypeInterface . JdbcType ; public class SqlMapping { private String tableName ; private HashMap < String , Column > fields ; private Column primaryColumn ; public SqlMapping ( ) { fields = new HashMap < String , Column > ( ) ; } public void setTableName ( String tableName ) { this . tableName = tableName ; } public String getTableName ( ) { return tableName ; } public void addField ( String fieldname , String column ) { fields . put ( fieldname , new Column ( column ) ) ; } public void addField ( String fieldName , String columnName , JdbcType jdbcType , String sqlType , int length , int scale ) { fields . put ( fieldName , new Column ( columnName , false , jdbcType , sqlType , length , scale ) ) ; } public Column getColumn ( String fieldname ) { return fields . get ( fieldname ) ; } public void setPrimaryKey ( String columnName , JdbcType jdbcType , int length , int scale ) { primaryColumn = new Column ( columnName , true , jdbcType , length , scale ) ; } public Column getPrimaryColumn ( ) { return primaryColumn ; } public String getPrimaryColumnName ( ) { return primaryColumn . getName ( ) ; } public HashMap < String , Column > getFields ( ) { return fields ; } } </s>
|
<s> package org . apache . gora . sql . store ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . nio . ByteBuffer ; import java . sql . Blob ; import java . sql . Connection ; import java . sql . DatabaseMetaData ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import org . apache . avro . Schema ; import org . apache . avro . Schema . Field ; import org . apache . avro . Schema . Type ; import org . apache . avro . generic . GenericFixed ; import org . apache . avro . ipc . ByteBufferInputStream ; import org . apache . avro . ipc . ByteBufferOutputStream ; import org . apache . avro . specific . SpecificFixed ; import org . apache . avro . util . Utf8 ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . persistency . StateManager ; import org . apache . gora . query . PartitionQuery ; import org . apache . gora . query . Query ; import org . apache . gora . query . Result ; import org . apache . gora . query . impl . PartitionQueryImpl ; import org . apache . gora . sql . query . SqlQuery ; import org . apache . gora . sql . query . SqlResult ; import org . apache . gora . sql . statement . Delete ; import org . apache . gora . sql . statement . InsertUpdateStatement ; import org . apache . gora . sql . statement . InsertUpdateStatementFactory ; import org . apache . gora . sql . statement . SelectStatement ; import org . apache . gora . sql . statement . Where ; import org . apache . gora . sql . store . SqlTypeInterface . JdbcType ; import org . apache . gora . sql . util . SqlUtils ; import org . apache . gora . store . DataStoreFactory ; import org . apache . gora . store . impl . DataStoreBase ; import org . apache . gora . util . AvroUtils ; import org . apache . gora . util . ClassLoadingUtils ; import org . apache . gora . util . IOUtils ; import org . apache . gora . util . StringUtils ; import org . jdom . Document ; import org . jdom . Element ; import org . jdom . input . SAXBuilder ; public class SqlStore < K , T extends Persistent > extends DataStoreBase < K , T > { public static enum DBVendor { MYSQL , HSQL , GENERIC ; static DBVendor getVendor ( String dbProductName ) { String name = dbProductName . toLowerCase ( ) ; if ( name . contains ( "<STR_LIT>" ) ) return MYSQL ; else if ( name . contains ( "<STR_LIT>" ) ) return HSQL ; return GENERIC ; } } private static final Logger log = LoggerFactory . getLogger ( SqlStore . class ) ; protected static final String DRIVER_CLASS_PROPERTY = "<STR_LIT>" ; protected static final String URL_PROPERTY = "<STR_LIT>" ; protected static final String USERNAME_PROPERTY = "<STR_LIT>" ; protected static final String PASSWORD_PROPERTY = "<STR_LIT>" ; protected static final String DEFAULT_MAPPING_FILE = "<STR_LIT>" ; private String jdbcDriverClass ; private String jdbcUrl ; private String jdbcUsername ; private String jdbcPassword ; private SqlMapping mapping ; private Connection connection ; private DatabaseMetaData metadata ; private boolean dbMixedCaseIdentifiers , dbLowerCaseIdentifiers , dbUpperCaseIdentifiers ; private HashMap < String , JdbcType > dbTypeMap ; private HashSet < PreparedStatement > writeCache ; private int keySqlType ; private Column primaryColumn ; private String dbProductName ; private DBVendor dbVendor ; public void initialize ( ) throws IOException { } @ Override public String getSchemaName ( ) { return mapping . getTableName ( ) ; } @ Override public void close ( ) throws IOException { } private void setColumnConstraintForQuery ( ) throws IOException { } @ Override public void createSchema ( ) throws IOException { } private void getColumnConstraint ( ) throws IOException { } @ Override public void deleteSchema ( ) throws IOException { } @ Override public boolean schemaExists ( ) throws IOException { return false ; } @ Override public boolean delete ( K key ) throws IOException { return false ; } @ Override public long deleteByQuery ( Query < K , T > query ) throws IOException { return <NUM_LIT:0> ; } public void flush ( ) throws IOException { } @ Override public T get ( K key , String [ ] requestFields ) throws IOException { return null ; } @ Override public Result < K , T > execute ( Query < K , T > query ) throws IOException { return null ; } private void constructWhereClause ( ) throws IOException { } private void setParametersForPreparedStatement ( ) throws SQLException , IOException { } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public K readPrimaryKey ( ResultSet resultSet ) throws SQLException { return ( K ) resultSet . getObject ( primaryColumn . getName ( ) ) ; } public T readObject ( ResultSet rs , T persistent , String [ ] requestFields ) throws SQLException , IOException { return null ; } protected byte [ ] getBytes ( ) throws SQLException , IOException { return null ; } protected Object readField ( ) throws SQLException , IOException { return null ; } public List < PartitionQuery < K , T > > getPartitions ( Query < K , T > query ) throws IOException { return null ; } @ Override public Query < K , T > newQuery ( ) { return new SqlQuery < K , T > ( this ) ; } @ Override public void put ( K key , T persistent ) throws IOException { } public void setObject ( PreparedStatement statement , int index , Object object , Schema schema , Column column ) throws SQLException , IOException { } protected < V > void setObject ( PreparedStatement statement , int index , V object , int objectType , Column column ) throws SQLException , IOException { statement . setObject ( index , object , objectType , column . getScaleOrLength ( ) ) ; } protected void setBytes ( ) throws SQLException { } protected void setField ( ) throws IOException , SQLException { } protected Connection getConnection ( ) throws IOException { return null ; } protected void initDbMetadata ( ) throws IOException { } protected String getIdentifier ( ) { return null ; } private void addColumn ( ) { } protected void createSqlTable ( ) { } private void addField ( ) throws IOException { } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) protected SqlMapping readMapping ( ) throws IOException { return null ; } } </s>
|
<s> package org . apache . gora . sql . statement ; public class Where { private StringBuilder builder ; public Where ( ) { builder = new StringBuilder ( ) ; } public Where ( String where ) { builder = new StringBuilder ( where == null ? "<STR_LIT>" : where ) ; } public void addPart ( String part ) { if ( builder . length ( ) > <NUM_LIT:0> ) { builder . append ( "<STR_LIT>" ) ; } builder . append ( part ) ; } public void equals ( String name , String value ) { addPart ( name + "<STR_LIT:U+0020=U+0020>" + value ) ; } public void lessThan ( String name , String value ) { addPart ( name + "<STR_LIT>" + value ) ; } public void lessThanEq ( String name , String value ) { addPart ( name + "<STR_LIT>" + value ) ; } public void greaterThan ( String name , String value ) { addPart ( name + "<STR_LIT>" + value ) ; } public void greaterThanEq ( String name , String value ) { addPart ( name + "<STR_LIT>" + value ) ; } public boolean isEmpty ( ) { return builder . length ( ) == <NUM_LIT:0> ; } @ Override public String toString ( ) { return builder . toString ( ) ; } } </s>
|
<s> package org . apache . gora . sql . statement ; import java . util . ArrayList ; import org . apache . gora . util . StringUtils ; public class SelectStatement { private String selectStatement ; private ArrayList < String > selectList ; private String from ; private Where where ; private String groupBy ; private String having ; private String orderBy ; private boolean orderByAsc = true ; private long offset = - <NUM_LIT:1> ; private long limit = - <NUM_LIT:1> ; private boolean semicolon = true ; public SelectStatement ( ) { this . selectList = new ArrayList < String > ( ) ; } public SelectStatement ( String from ) { this ( ) ; this . from = from ; } public SelectStatement ( String selectList , String from , String where , String orderBy ) { this . selectStatement = selectList ; this . from = from ; setWhere ( where ) ; this . orderBy = orderBy ; } public SelectStatement ( String selectList , String from , Where where , String groupBy , String having , String orderBy , boolean orderByAsc , int offset , int limit , boolean semicolon ) { super ( ) ; this . selectStatement = selectList ; this . from = from ; this . where = where ; this . groupBy = groupBy ; this . having = having ; this . orderBy = orderBy ; this . orderByAsc = orderByAsc ; this . offset = offset ; this . limit = limit ; this . semicolon = semicolon ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( "<STR_LIT>" ) ; if ( selectStatement != null ) builder . append ( selectStatement ) ; else StringUtils . join ( builder , selectList ) ; append ( builder , "<STR_LIT>" , from ) ; append ( builder , "<STR_LIT>" , where ) ; append ( builder , "<STR_LIT>" , groupBy ) ; append ( builder , "<STR_LIT>" , having ) ; append ( builder , "<STR_LIT>" , orderBy ) ; if ( orderBy != null ) builder . append ( "<STR_LIT:U+0020>" ) . append ( orderByAsc ? "<STR_LIT>" : "<STR_LIT>" ) ; if ( limit > <NUM_LIT:0> ) builder . append ( "<STR_LIT>" ) . append ( limit ) ; if ( offset >= <NUM_LIT:0> ) builder . append ( "<STR_LIT>" ) . append ( offset ) ; if ( semicolon ) builder . append ( "<STR_LIT:;>" ) ; return builder . toString ( ) ; } public void addWhere ( String part ) { if ( where == null ) where = new Where ( ) ; where . addPart ( part ) ; } static void append ( StringBuilder builder , String sqlClause , Object clause ) { if ( clause != null && ! clause . toString ( ) . equals ( "<STR_LIT>" ) ) { builder . append ( "<STR_LIT:U+0020>" ) . append ( sqlClause ) . append ( "<STR_LIT:U+0020>" ) . append ( clause . toString ( ) ) ; } } public void setSelectStatement ( String selectStatement ) { this . selectStatement = selectStatement ; } public String getSelectStatement ( ) { return selectStatement ; } public ArrayList < String > getSelectList ( ) { return selectList ; } public void setSelectList ( ArrayList < String > selectList ) { this . selectList = selectList ; } public void addToSelectList ( String selectField ) { selectList . add ( selectField ) ; } public String getFrom ( ) { return from ; } public void setFrom ( String from ) { this . from = from ; } public Where getWhere ( ) { return where ; } public void setWhere ( Where where ) { this . where = where ; } public void setWhere ( String where ) { this . where = new Where ( where ) ; } public String getGroupBy ( ) { return groupBy ; } public void setGroupBy ( String groupBy ) { this . groupBy = groupBy ; } public String getHaving ( ) { return having ; } public void setHaving ( String having ) { this . having = having ; } public String getOrderBy ( ) { return orderBy ; } public void setOrderBy ( String orderBy ) { this . orderBy = orderBy ; } public boolean isOrderByAsc ( ) { return orderByAsc ; } public void setOrderByAsc ( boolean orderByAsc ) { this . orderByAsc = orderByAsc ; } public long getOffset ( ) { return offset ; } public void setOffset ( long offset ) { this . offset = offset ; } public long getLimit ( ) { return limit ; } public void setLimit ( long limit ) { this . limit = limit ; } public boolean isSemicolon ( ) { return semicolon ; } public void setSemicolon ( boolean semicolon ) { this . semicolon = semicolon ; } } </s>
|
<s> package org . apache . gora . sql . statement ; public class Delete { private String from ; private Where where ; public String from ( ) { return from ; } public Delete from ( String from ) { this . from = from ; return this ; } public Delete where ( Where where ) { this . where = where ; return this ; } public Where where ( ) { if ( where == null ) { where = new Where ( ) ; } return where ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( "<STR_LIT>" ) ; builder . append ( from ) ; if ( where != null && ! where . isEmpty ( ) ) { builder . append ( "<STR_LIT>" ) ; builder . append ( where . toString ( ) ) ; } return builder . toString ( ) ; } } </s>
|
<s> package org . apache . gora . sql . statement ; import java . io . IOException ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . SQLException ; import java . util . Map . Entry ; import org . apache . avro . Schema ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . sql . store . Column ; import org . apache . gora . sql . store . SqlMapping ; import org . apache . gora . sql . store . SqlStore ; import org . apache . gora . util . StringUtils ; public class MySqlInsertUpdateStatement < K , V extends Persistent > extends InsertUpdateStatement < K , V > { public MySqlInsertUpdateStatement ( SqlStore < K , V > store , SqlMapping mapping , String tableName ) { super ( store , mapping , tableName ) ; } @ Override public PreparedStatement toStatement ( Connection connection ) throws SQLException { int i = <NUM_LIT:0> ; StringBuilder builder = new StringBuilder ( "<STR_LIT>" ) ; builder . append ( tableName ) ; StringUtils . join ( builder . append ( "<STR_LIT:U+0020(>" ) , columnMap . keySet ( ) ) . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; for ( i = <NUM_LIT:0> ; i < columnMap . size ( ) ; i ++ ) { if ( i != <NUM_LIT:0> ) builder . append ( "<STR_LIT:U+002C>" ) ; builder . append ( "<STR_LIT:?>" ) ; } builder . append ( "<STR_LIT>" ) ; Column primaryColumn = mapping . getPrimaryColumn ( ) ; Object key = columnMap . get ( primaryColumn . getName ( ) ) . object ; i = <NUM_LIT:0> ; for ( String s : columnMap . keySet ( ) ) { if ( s . equals ( primaryColumn . getName ( ) ) ) { continue ; } if ( i != <NUM_LIT:0> ) builder . append ( "<STR_LIT:U+002C>" ) ; builder . append ( s ) . append ( "<STR_LIT:=>" ) . append ( "<STR_LIT:?>" ) ; i ++ ; } builder . append ( "<STR_LIT:;>" ) ; PreparedStatement insert = connection . prepareStatement ( builder . toString ( ) ) ; int psIndex = <NUM_LIT:1> ; for ( int count = <NUM_LIT:0> ; count < <NUM_LIT:2> ; count ++ ) { for ( Entry < String , ColumnData > e : columnMap . entrySet ( ) ) { ColumnData columnData = e . getValue ( ) ; Column column = columnData . column ; Schema fieldSchema = columnData . schema ; Object fieldValue = columnData . object ; if ( column . getName ( ) . equals ( primaryColumn . getName ( ) ) ) { if ( count == <NUM_LIT:1> ) { continue ; } if ( primaryColumn . getScaleOrLength ( ) > <NUM_LIT:0> ) { insert . setObject ( psIndex ++ , key , primaryColumn . getJdbcType ( ) . getOrder ( ) , primaryColumn . getScaleOrLength ( ) ) ; } else { insert . setObject ( psIndex ++ , key , primaryColumn . getJdbcType ( ) . getOrder ( ) ) ; } continue ; } try { store . setObject ( insert , psIndex ++ , fieldValue , fieldSchema , column ) ; } catch ( IOException ex ) { throw new SQLException ( ex ) ; } } } return insert ; } } </s>
|
<s> package org . apache . gora . sql . statement ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . sql . store . SqlMapping ; import org . apache . gora . sql . store . SqlStore ; import org . apache . gora . sql . store . SqlStore . DBVendor ; public class InsertUpdateStatementFactory { public static < K , T extends Persistent > InsertUpdateStatement < K , T > createStatement ( SqlStore < K , T > store , SqlMapping mapping , DBVendor dbVendor ) { switch ( dbVendor ) { case MYSQL : return new MySqlInsertUpdateStatement < K , T > ( store , mapping , mapping . getTableName ( ) ) ; case HSQL : return new HSqlInsertUpdateStatement < K , T > ( store , mapping , mapping . getTableName ( ) ) ; case GENERIC : default : throw new RuntimeException ( "<STR_LIT>" ) ; } } } </s>
|
<s> package org . apache . gora . sql . statement ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . SQLException ; import java . util . SortedMap ; import java . util . TreeMap ; import org . apache . avro . Schema ; import org . apache . gora . persistency . Persistent ; import org . apache . gora . sql . store . Column ; import org . apache . gora . sql . store . SqlMapping ; import org . apache . gora . sql . store . SqlStore ; public abstract class InsertUpdateStatement < K , V extends Persistent > { protected class ColumnData { protected Object object ; protected Schema schema ; protected Column column ; protected ColumnData ( Object object , Schema schema , Column column ) { this . object = object ; this . schema = schema ; this . column = column ; } } protected SortedMap < String , ColumnData > columnMap = new TreeMap < String , ColumnData > ( ) ; protected String tableName ; protected SqlMapping mapping ; protected SqlStore < K , V > store ; public InsertUpdateStatement ( SqlStore < K , V > store , SqlMapping mapping , String tableName ) { this . store = store ; this . mapping = mapping ; this . tableName = tableName ; } public void setObject ( Object object , Schema schema , Column column ) { columnMap . put ( column . getName ( ) , new ColumnData ( object , schema , column ) ) ; } public abstract PreparedStatement toStatement ( Connection connection ) throws SQLException ; } </s>
|
<s> package org . apache . gora . sql . statement ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . apache . gora . sql . store . SqlMapping ; import org . apache . gora . util . StringUtils ; public class InsertStatement { private SqlMapping mapping ; private String tableName ; private List < String > columnNames ; public InsertStatement ( SqlMapping mapping , String tableName ) { this . mapping = mapping ; this . tableName = tableName ; this . columnNames = new ArrayList < String > ( ) ; } public InsertStatement ( SqlMapping mapping , String tableName , String ... columnNames ) { this . mapping = mapping ; this . tableName = tableName ; this . columnNames = Arrays . asList ( columnNames ) ; } @ Override public String toString ( ) { StringBuilder builder = new StringBuilder ( "<STR_LIT>" ) ; builder . append ( tableName ) ; StringUtils . join ( builder . append ( "<STR_LIT:U+0020(>" ) , columnNames ) . append ( "<STR_LIT>" ) ; builder . append ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < columnNames . size ( ) ; i ++ ) { if ( i != <NUM_LIT:0> ) builder . append ( "<STR_LIT:U+002C>" ) ; builder . append ( "<STR_LIT:?>" ) ; } builder . append ( "<STR_LIT>" ) ; columnNames . remove ( mapping . getPrimaryColumnName ( ) ) ; for ( int i = <NUM_LIT:0> ; i < columnNames . size ( ) ; i ++ ) { if ( i != <NUM_LIT:0> ) builder . append ( "<STR_LIT:U+002C>" ) ; builder . append ( columnNames . get ( i ) ) ; builder . append ( "<STR_LIT:=>" ) ; builder . append ( "<STR_LIT:?>" ) ; } builder . append ( "<STR_LIT:;>" ) ; return builder . toString ( ) ; } public String getTableName ( ) { return tableName ; } public void setTableName ( String tableName ) { this . tableName = tableName ; } public List < String > getColumnNames ( ) { return columnNames ; } public void setColumnNames ( String ... columnNames ) { this . columnNames = Arrays . asList ( columnNames ) ; } public void addColumnName ( String columnName ) { this . columnNames . add ( columnName ) ; } public void clear ( ) { this . columnNames . clear ( ) ; } } </s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.