proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/ide/syntaxhighlight/style/ColorStyleElement.java
ColorStyleElement
getColorStyleElementByName
class ColorStyleElement extends StyleElement { // // Types // public enum Type { Foreground, Background, Border } // // Static attributes // public static ColorStyleElement getColorStyleElementByName( String name ) {<FILL_FUNCTION_BODY>} public static ColorStyleElement foreground( String color ) { return new ColorStyleElement( color, Type.Foreground, color ); } public static ColorStyleElement background( String color ) { return new ColorStyleElement( "bg:" + color, Type.Background, color ); } public static ColorStyleElement border( String color ) { return new ColorStyleElement( "border:" + color, Type.Border, color ); } // // Attributes // public String getColor() { return color; } public Type getType() { return type; } // ////////////////////////////////////////////////////////////////////////// // Protected protected ColorStyleElement( String name, Type type, String color ) { super( name ); this.type = type; this.color = color; } // ////////////////////////////////////////////////////////////////////////// // Private private final String color; private final Type type; }
if( name.startsWith( "bg:" ) ) return background( name.substring( 3 ) ); if( name.startsWith( "border:" ) ) return border( name.substring( 7 ) ); return foreground( name );
308
69
377
<methods>public java.lang.String getName() ,public static org.sikuli.support.ide.syntaxhighlight.style.StyleElement getStyleElementByName(java.lang.String) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String name,private static Map<java.lang.String,org.sikuli.support.ide.syntaxhighlight.style.StyleElement> styleElementsByName
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/ide/syntaxhighlight/style/EffectStyleElement.java
EffectStyleElement
create
class EffectStyleElement extends StyleElement { // // Constants // public static final EffectStyleElement Bold = create( "bold" ); public static final EffectStyleElement NoBold = create( "nobold" ); public static final EffectStyleElement Italic = create( "italic" ); public static final EffectStyleElement NoItalic = create( "noitalic" ); public static final EffectStyleElement Underline = create( "underline" ); public static final EffectStyleElement NoUnderline = create( "nounderline" ); // ////////////////////////////////////////////////////////////////////////// // Protected protected EffectStyleElement( String name ) { super( name ); } private static EffectStyleElement create( String name ) {<FILL_FUNCTION_BODY>} }
EffectStyleElement fontStyleElement = new EffectStyleElement( name ); add( fontStyleElement ); return fontStyleElement;
195
36
231
<methods>public java.lang.String getName() ,public static org.sikuli.support.ide.syntaxhighlight.style.StyleElement getStyleElementByName(java.lang.String) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String name,private static Map<java.lang.String,org.sikuli.support.ide.syntaxhighlight.style.StyleElement> styleElementsByName
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/ide/syntaxhighlight/style/FontStyleElement.java
FontStyleElement
create
class FontStyleElement extends StyleElement { // // Constants // public static final FontStyleElement Roman = create( "roman" ); public static final FontStyleElement Sans = create( "sans" ); public static final FontStyleElement Mono = create( "mono" ); // ////////////////////////////////////////////////////////////////////////// // Protected protected FontStyleElement( String name ) { super( name ); } private static FontStyleElement create( String name ) {<FILL_FUNCTION_BODY>} }
FontStyleElement fontStyleElement = new FontStyleElement( name ); add( fontStyleElement ); return fontStyleElement;
133
36
169
<methods>public java.lang.String getName() ,public static org.sikuli.support.ide.syntaxhighlight.style.StyleElement getStyleElementByName(java.lang.String) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String name,private static Map<java.lang.String,org.sikuli.support.ide.syntaxhighlight.style.StyleElement> styleElementsByName
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/ide/syntaxhighlight/style/Style.java
Style
getByName
class Style extends NestedDef<Style> { static String extJSON = ".jso"; // // Static operations // public static Style getByName( String name ) throws ResolutionException {<FILL_FUNCTION_BODY>} public static Style getByFullName( String name ) throws ResolutionException { return getByFullName("", "", name); } @SuppressWarnings("unchecked") public static Style getByFullName( String pack, String sub, String name ) throws ResolutionException { String fullname = name; if (!pack.isEmpty()) { if (!sub.isEmpty()) { fullname = pack + "." + sub + "." + fullname; } else { fullname = pack + "." + fullname; } } // Try cache Style style = styles.get( fullname ); if( style != null ) return style; try { return (Style) Jygments.class.getClassLoader().loadClass( fullname ).newInstance(); } catch( InstantiationException x ) { } catch( IllegalAccessException x ) { } catch( ClassNotFoundException x ) { } InputStream stream = Util.getJsonFile(pack, sub, name, fullname); if( stream != null ) { ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.getFactory().configure( JsonParser.Feature.ALLOW_COMMENTS, true ); try { Map<String, Object> json = objectMapper.readValue( stream, HashMap.class ); style = new Style(); style.addJson( json ); style.resolve(); // Cache it Style existing = styles.putIfAbsent( fullname, style ); if( existing != null ) style = existing; return style; } catch( JsonParseException x ) { throw new ResolutionException( x ); } catch( JsonMappingException x ) { throw new ResolutionException( x ); } catch( IOException x ) { throw new ResolutionException( x ); } } return null; } // // Attributes // public Map<TokenType, List<StyleElement>> getStyleElements() { return styleElements; } // // Operations // public void addStyleElement( TokenType tokenType, StyleElement styleElement ) { List<StyleElement> styleElementsForTokenType = styleElements.get( tokenType ); if( styleElementsForTokenType == null ) { styleElementsForTokenType = new ArrayList<StyleElement>(); styleElements.put( tokenType, styleElementsForTokenType ); } styleElementsForTokenType.add( styleElement ); } public void resolve() throws ResolutionException { resolve( this ); } // // Def // @Override public boolean resolve( Style style ) throws ResolutionException { if( super.resolve( style ) ) { boolean done = false; while( !done ) { done = true; for( TokenType tokenType : TokenType.getTokenTypes() ) { if( tokenType != TokenType.Token ) { if( !styleElements.containsKey( tokenType ) ) { boolean doneOne = false; TokenType parent = tokenType.getParent(); while( parent != null ) { if( parent == TokenType.Token ) { doneOne = true; break; } List<StyleElement> parentElements = styleElements.get( parent ); if( parentElements != null ) { styleElements.put( tokenType, parentElements ); doneOne = true; break; } parent = parent.getParent(); } if( !doneOne ) done = false; } } } } return true; } else return false; } // ////////////////////////////////////////////////////////////////////////// // Protected protected void add( String tokenTypeName, String... styleElementNames ) { ArrayList<String> list = new ArrayList<String>( styleElementNames.length ); for( String styleElementName : styleElementNames ) list.add( styleElementName ); addDef( new StyleElementDef( tokenTypeName, list ) ); } @SuppressWarnings("unchecked") protected void addJson( Map<String, Object> json ) throws ResolutionException { for( Map.Entry<String, Object> entry : json.entrySet() ) { String tokenTypeName = entry.getKey(); if( entry.getValue() instanceof Iterable<?> ) { for( String styleElementName : (Iterable<String>) entry.getValue() ) add( tokenTypeName, styleElementName ); } else if( entry.getValue() instanceof String ) add( tokenTypeName, (String) entry.getValue() ); else throw new ResolutionException( "Unexpected value in style definition: " + entry.getValue() ); } } // ////////////////////////////////////////////////////////////////////////// // Private private static final ConcurrentMap<String, Style> styles = new ConcurrentHashMap<String, Style>(); private final Map<TokenType, List<StyleElement>> styleElements = new HashMap<TokenType, List<StyleElement>>(); }
if( Character.isLowerCase( name.charAt( 0 ) ) ) name = Character.toUpperCase( name.charAt( 0 ) ) + name.substring( 1 ) + "Style"; Style style = getByFullName( name ); if( style != null ) return style; else { // Try contrib package String pack = Jygments.class.getPackage().getName(); return getByFullName( pack, "contrib", name ); }
1,418
131
1,549
<methods>public non-sealed void <init>() ,public void addDef(Def<org.sikuli.support.ide.syntaxhighlight.style.Style>) ,public Def<org.sikuli.support.ide.syntaxhighlight.style.Style> getCause(org.sikuli.support.ide.syntaxhighlight.style.Style) ,public boolean resolve(org.sikuli.support.ide.syntaxhighlight.style.Style) throws org.sikuli.support.ide.syntaxhighlight.ResolutionException<variables>private final List<Def<org.sikuli.support.ide.syntaxhighlight.style.Style>> defs
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/ide/syntaxhighlight/style/StyleElement.java
StyleElement
getStyleElementByName
class StyleElement { static { // Force these classes to load new ColorStyleElement( null, null, null ); new EffectStyleElement( null ); new FontStyleElement( null ); } // // Static attributes // public static StyleElement getStyleElementByName( String name ) {<FILL_FUNCTION_BODY>} // // Attributes // public String getName() { return name; } // // Object // @Override public String toString() { return name; } // ////////////////////////////////////////////////////////////////////////// // Protected protected static final void add( StyleElement styleElement ) { if( styleElementsByName == null ) styleElementsByName = new HashMap<String, StyleElement>(); styleElementsByName.put( styleElement.name, styleElement ); } protected StyleElement( String name ) { this.name = name; } // ////////////////////////////////////////////////////////////////////////// // Private private static Map<String, StyleElement> styleElementsByName; private final String name; }
StyleElement styleElement = styleElementsByName.get( name ); if( styleElement == null ) styleElement = ColorStyleElement.getColorStyleElementByName( name ); return styleElement;
281
54
335
<no_super_class>
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/ide/syntaxhighlight/style/def/StyleElementDef.java
StyleElementDef
resolve
class StyleElementDef extends Def<Style> { // // Construction // public StyleElementDef( String tokenTypeName, List<String> styleElementNames ) { this.tokenTypeName = tokenTypeName; this.styleElementNames = styleElementNames; } // // Def // @Override public boolean resolve( Style style ) throws ResolutionException {<FILL_FUNCTION_BODY>} // ////////////////////////////////////////////////////////////////////////// // Private private final String tokenTypeName; private final List<String> styleElementNames; }
TokenType tokenType = TokenType.getTokenTypeByName( tokenTypeName ); if( tokenType == null ) throw new ResolutionException( "Unknown token type: " + tokenTypeName ); //TokenType parent = tokenType.getParent(); //boolean addToParent = false; //if( ( parent != null ) && ( !style.getStyleElements().containsKey( parent ) ) ) //addToParent = true; for( String styleElementName : styleElementNames ) { StyleElement styleElement = StyleElement.getStyleElementByName( styleElementName ); if( styleElement == null ) throw new ResolutionException( "Unknown style element: " + styleElementName ); style.addStyleElement( tokenType, styleElement ); //if( addToParent ) //style.addStyleElement( parent, styleElement ); } resolved = true; return true;
138
235
373
<methods>public non-sealed void <init>() ,public Def<org.sikuli.support.ide.syntaxhighlight.style.Style> getCause(org.sikuli.support.ide.syntaxhighlight.style.Style) ,public boolean isResolved() ,public boolean resolve(org.sikuli.support.ide.syntaxhighlight.style.Style) throws org.sikuli.support.ide.syntaxhighlight.ResolutionException,public java.lang.String toString() <variables>protected boolean resolved
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/AbortableScriptRunnerWrapper.java
AbortableScriptRunnerWrapper
isAbortSupported
class AbortableScriptRunnerWrapper { private Object runnerLock = new Object(); private IRunner runner; public IRunner getRunner() { synchronized(runnerLock) { return runner; } } public void setRunner(IRunner runner) { synchronized(runnerLock) { this.runner = runner; } } public void clearRunner() { synchronized(runnerLock) { this.runner = null; } } public boolean isAbortSupported() {<FILL_FUNCTION_BODY>} public void doAbort() { synchronized(runnerLock) { if (isAbortSupported()) { runner.abort(); } } } }
synchronized(runnerLock) { return null != runner && runner.isAbortSupported(); }
197
31
228
<no_super_class>
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/AbstractLocalFileScriptRunner.java
AbstractLocalFileScriptRunner
canHandle
class AbstractLocalFileScriptRunner extends AbstractRunner { private static final Deque<String> PREVIOUS_BUNDLE_PATHS = new ConcurrentLinkedDeque<>(); @Override protected void adjustBundlePath(String script, IRunner.Options options) { File file = new File(script); if (file.exists()) { String currentBundlePath = ImagePath.getBundlePath(); if(currentBundlePath != null) { PREVIOUS_BUNDLE_PATHS.push(currentBundlePath); } ImagePath.setBundleFolder(file.getParentFile()); } } @Override protected void resetBundlePath(String script, IRunner.Options options) { if (new File(script).exists() && !PREVIOUS_BUNDLE_PATHS.isEmpty()) { ImagePath.setBundlePath(PREVIOUS_BUNDLE_PATHS.pop()); } } @Override public boolean canHandle(String identifier) {<FILL_FUNCTION_BODY>} public void checkAndSetConsole() { if (!consoleChecked()) { setConsole(SikulixIDE.get().getConsole()); consoleChecked(true); } } }
if (identifier != null) { /* * Test if we have a network protocol in front of the identifier. In such a case * we cannot handle the identifier directly */ int protoSepIndex = identifier.indexOf("://"); if (protoSepIndex > 0 && protoSepIndex <= 5) { return false; } return super.canHandle(identifier); } return false;
319
106
425
<methods>public non-sealed void <init>() ,public final void abort() ,public boolean canHandle(java.lang.String) ,public final boolean canHandleFileEnding(java.lang.String) ,public void checkAndSetConsole() ,public final void close() ,public boolean consoleChecked() ,public void consoleChecked(boolean) ,public final int evalScript(java.lang.String, org.sikuli.support.runner.IRunner.Options) ,public void execAfter(java.lang.String[]) ,public void execBefore(java.lang.String[]) ,public java.lang.String getDefaultExtension() ,public org.sikuli.support.runner.IRunner.EffectiveRunner getEffectiveRunner(java.lang.String) ,public java.lang.String[] getFileEndings() ,public final boolean hasExtension(java.lang.String) ,public final void init(java.lang.String[]) throws org.sikuli.script.SikuliXception,public boolean isAbortSupported() ,public final boolean isAborted() ,public final boolean isReady() ,public final boolean isRunning() ,public boolean isSupported() ,public final void redirect(java.io.PrintStream, java.io.PrintStream) ,public final void reset() ,public final void runLines(java.lang.String, org.sikuli.support.runner.IRunner.Options) ,public final int runScript(java.lang.String, java.lang.String[], org.sikuli.support.runner.IRunner.Options) ,public void setConsole(java.lang.Object) <variables>public static final int NOT_SUPPORTED,private static final java.util.concurrent.ScheduledExecutorService TIMEOUT_EXECUTOR,private static final java.lang.Object WORKER_LOCK,private boolean aborted,static ArrayList<java.lang.String> codeAfter,static ArrayList<java.lang.String> codeBefore,private java.lang.Object console,private boolean consoleChecked,private boolean ready,private boolean running,private static volatile java.lang.Thread worker
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/InvalidRunner.java
InvalidRunner
getName
class InvalidRunner extends AbstractRunner { String identifier; public InvalidRunner() {} public InvalidRunner(String identifier) { super(); this.identifier = identifier; } public InvalidRunner(Class<? extends IRunner> cl) { this(cl.getName()); } @Override public String getName() {<FILL_FUNCTION_BODY>} @Override public String[] getExtensions() { // TODO Auto-generated method stub return new String[]{}; } public EffectiveRunner getEffectiveRunner(String script) { return new EffectiveRunner(this, null, false); } @Override public String getType() { return "invalid/" + identifier; } protected int doRunScript(String scriptfile, String[] scriptArgs, IRunner.Options options) { Debug.error("no runner available for: %s", new File(scriptfile).getName()); return Runner.NOT_SUPPORTED; } }
if (null == identifier) { return "InvalidRunner"; } return "InvalidRunner: " + identifier;
257
33
290
<methods>public non-sealed void <init>() ,public final void abort() ,public boolean canHandle(java.lang.String) ,public final boolean canHandleFileEnding(java.lang.String) ,public void checkAndSetConsole() ,public final void close() ,public boolean consoleChecked() ,public void consoleChecked(boolean) ,public final int evalScript(java.lang.String, org.sikuli.support.runner.IRunner.Options) ,public void execAfter(java.lang.String[]) ,public void execBefore(java.lang.String[]) ,public java.lang.String getDefaultExtension() ,public org.sikuli.support.runner.IRunner.EffectiveRunner getEffectiveRunner(java.lang.String) ,public java.lang.String[] getFileEndings() ,public final boolean hasExtension(java.lang.String) ,public final void init(java.lang.String[]) throws org.sikuli.script.SikuliXception,public boolean isAbortSupported() ,public final boolean isAborted() ,public final boolean isReady() ,public final boolean isRunning() ,public boolean isSupported() ,public final void redirect(java.io.PrintStream, java.io.PrintStream) ,public final void reset() ,public final void runLines(java.lang.String, org.sikuli.support.runner.IRunner.Options) ,public final int runScript(java.lang.String, java.lang.String[], org.sikuli.support.runner.IRunner.Options) ,public void setConsole(java.lang.Object) <variables>public static final int NOT_SUPPORTED,private static final java.util.concurrent.ScheduledExecutorService TIMEOUT_EXECUTOR,private static final java.lang.Object WORKER_LOCK,private boolean aborted,static ArrayList<java.lang.String> codeAfter,static ArrayList<java.lang.String> codeBefore,private java.lang.Object console,private boolean consoleChecked,private boolean ready,private boolean running,private static volatile java.lang.Thread worker
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/JRubyRunner.java
JRubyRunner
doRunScript
class JRubyRunner extends AbstractLocalFileScriptRunner { public static final String NAME = "JRuby"; public static final String TYPE = "text/ruby"; public static final String[] EXTENSIONS = new String[]{"rb"}; //<editor-fold desc="00 initialization"> @Override public boolean isAbortSupported() { return true; } @Override public boolean isSupported() { return jrubySupport.isSupported(); } @Override public String getName() { return NAME; } @Override public String[] getExtensions() { return EXTENSIONS.clone(); } @Override public String getType() { return TYPE; } @Override public void doClose() { jrubySupport.interpreterTerminate(); redirected = false; } static JRubySupport jrubySupport = null; private int lvl = 3; @Override protected void doInit(String[] args) { // Since we have a static interpreter, we have to synchronize class wide synchronized (JRubyRunner.class) { if (null == jrubySupport) { jrubySupport = JRubySupport.get(); // execute script headers to already do the warmup during init jrubySupport.executeScriptHeader(codeBefore); } } } //</editor-fold> private String injectAbortWatcher(String script) { return "Thread.new(){\n" + " runner = org.sikuli.support.ide.Runner.getRunner(\"" + NAME + "\")\n" + " while runner.isRunning()\n" + " sleep(0.1)\n" + " if runner.isAborted()\n" + " exit!\n" + " end\n" + " end\n" + "}\n" + script; } private int injectAbortWatcherLineCount() { return injectAbortWatcher("").split("\n").length; } //<editor-fold desc="10 run scripts"> @Override protected int doRunScript(String scriptFile, String[] scriptArgs, IRunner.Options options) {<FILL_FUNCTION_BODY>} @Override protected void doRunLines(String lines, IRunner.Options options) { // Since we have a static interpreter, we have to synchronize class wide synchronized (JRubyRunner.class) { try { lines = injectAbortWatcher(lines); jrubySupport.interpreterRunScriptletString(lines); } catch (Exception ex) { } } } @Override protected int doEvalScript(String script, IRunner.Options options) { // Since we have a static interpreter, we have to synchronize class wide synchronized (JRubyRunner.class) { script = injectAbortWatcher(script); jrubySupport.executeScriptHeader(codeBefore); jrubySupport.interpreterRunScriptletString(script); return 0; } } //</editor-fold> //<editor-fold desc="20 redirect"> private static boolean redirected = false; @Override protected boolean doRedirect(PrintStream stdout, PrintStream stderr) { //TODO extra redirect for interpreter needed? for what? // Since we have a static interpreter, we have to synchronize class wide // synchronized (JRubyRunner.class) { // if (!redirected) { // redirected = true; // return jrubySupport.interpreterRedirect(stdout, stderr); // } // return true; // } return true; } @Override protected void doAbort() { // Do nothing } //</editor-fold> }
// Since we have a static interpreter, we have to synchronize class wide Integer exitCode = 0; Object exitValue = null; synchronized (JRubyRunner.class) { File rubyFile = new File(new File(scriptFile).getAbsolutePath()); jrubySupport.fillSysArgv(rubyFile, scriptArgs); jrubySupport.executeScriptHeader(codeBefore, rubyFile.getParentFile().getAbsolutePath(), rubyFile.getParentFile().getParentFile().getAbsolutePath()); String script; try { script = FileUtils.readFileToString(rubyFile, "UTF-8"); } catch (IOException ex) { log(-1, "reading script: %s", ex.getMessage()); return Runner.FILE_NOT_FOUND; } script = injectAbortWatcher(script); try { //TODO handle exitValue (the result of the last line in the script or the value returned by statement return something) exitValue = jrubySupport.interpreterRunScriptletString(script); } catch (Throwable scriptException) { if(!isAborted()) { java.util.regex.Pattern p = java.util.regex.Pattern.compile("SystemExit: ([0-9]+)"); Matcher matcher = p.matcher(scriptException.toString()); if (matcher.find()) { exitCode = Integer.parseInt(matcher.group(1)); Debug.info("Exit code: " + exitCode); } else { //TODO to be optimized (avoid double message) int errorExit = jrubySupport.findErrorSource(scriptException, rubyFile.getAbsolutePath(), injectAbortWatcherLineCount()); options.setErrorLine(errorExit); } } } return exitCode; }
1,029
468
1,497
<methods>public non-sealed void <init>() ,public boolean canHandle(java.lang.String) ,public void checkAndSetConsole() <variables>private static final Deque<java.lang.String> PREVIOUS_BUNDLE_PATHS
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/NetworkRunner.java
NetworkRunner
getScriptURL
class NetworkRunner extends AbstractRunner { private AbortableScriptRunnerWrapper wrapper = new AbortableScriptRunnerWrapper(); @Override protected int doRunScript(String scriptFile, String[] scriptArgs, IRunner.Options options) { String scriptUrl = getScriptURL(scriptFile); if (null != scriptUrl) { File dir = null; try { dir = Files.createTempDirectory("sikulix").toFile(); String localFile = FileManager.downloadURL(scriptUrl, dir.getAbsolutePath()); if (localFile != null) { IRunner runner = Runner.getRunner(localFile); wrapper.setRunner(runner); int retval = runner.runScript(localFile, scriptArgs, options); return retval; } } catch (IOException e) { log(-1, "Error creating tmpfile: %s", e.getMessage()); } finally { wrapper.clearRunner(); if (null != dir) { try { FileUtils.deleteDirectory(dir); } catch (IOException e) { log(-1, "Error deleting tmp dir %s: %s", dir, e.getMessage()); } } } } log(-1, "given script location not supported or not valid:\n%s", scriptFile); return -1; } @Override public boolean isSupported() { return true; } @Override public String getName() { return "NetworkRunner"; } @Override public boolean canHandle(String identifier) { if (identifier != null) { int protoSepIndex = identifier.indexOf("://"); if (protoSepIndex > 0 && protoSepIndex <= 5) { String[] parts = identifier.split("://"); if (parts.length > 1 && !parts[1].isEmpty()) { return null != getScriptURL(identifier); } } } return false; } public String resolveRelativeFile(String script) { return script; } private String getScriptURL(String scriptFile) {<FILL_FUNCTION_BODY>} @Override public String[] getExtensions() { // TODO Auto-generated method stub return new String[0]; } @Override public String getType() { return "NET"; } @Override public boolean isAbortSupported() { return wrapper.isAbortSupported(); } @Override protected void doAbort() { wrapper.doAbort(); } @Override protected void adjustBundlePath(String script, IRunner.Options options) { String identifierParent = script.substring(0, script.lastIndexOf("/")); ImagePath.addHTTP(identifierParent); } @Override protected void resetBundlePath(String script, IRunner.Options options) { String identifierParent = script.substring(0, script.lastIndexOf("/")); ImagePath.removeHTTP(identifierParent); } }
URL scriptURL; try { scriptURL = new URL(scriptFile); String path = scriptURL.getPath(); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } String basename = FilenameUtils.getBaseName(path); String host = scriptURL.getHost(); if (host.contains("github.com")) { host = "https://raw.githubusercontent.com"; path = path.replace("tree/", ""); } else { host = scriptFile.substring(0, scriptFile.indexOf(path)); } String identifier = host + path; for (IRunner runner : Runner.getRunners()) { for (String ending : runner.getFileEndings()) { String url; if (identifier.endsWith(ending)) { url = identifier; } else { url = identifier + "/" + basename + ending; } if (FileManager.isUrlUseabel(url) > 0) { return url; } } } } catch (MalformedURLException e) { log(-1, "Invalid URL:\n%s", scriptFile); } return null;
780
329
1,109
<methods>public non-sealed void <init>() ,public final void abort() ,public boolean canHandle(java.lang.String) ,public final boolean canHandleFileEnding(java.lang.String) ,public void checkAndSetConsole() ,public final void close() ,public boolean consoleChecked() ,public void consoleChecked(boolean) ,public final int evalScript(java.lang.String, org.sikuli.support.runner.IRunner.Options) ,public void execAfter(java.lang.String[]) ,public void execBefore(java.lang.String[]) ,public java.lang.String getDefaultExtension() ,public org.sikuli.support.runner.IRunner.EffectiveRunner getEffectiveRunner(java.lang.String) ,public java.lang.String[] getFileEndings() ,public final boolean hasExtension(java.lang.String) ,public final void init(java.lang.String[]) throws org.sikuli.script.SikuliXception,public boolean isAbortSupported() ,public final boolean isAborted() ,public final boolean isReady() ,public final boolean isRunning() ,public boolean isSupported() ,public final void redirect(java.io.PrintStream, java.io.PrintStream) ,public final void reset() ,public final void runLines(java.lang.String, org.sikuli.support.runner.IRunner.Options) ,public final int runScript(java.lang.String, java.lang.String[], org.sikuli.support.runner.IRunner.Options) ,public void setConsole(java.lang.Object) <variables>public static final int NOT_SUPPORTED,private static final java.util.concurrent.ScheduledExecutorService TIMEOUT_EXECUTOR,private static final java.lang.Object WORKER_LOCK,private boolean aborted,static ArrayList<java.lang.String> codeAfter,static ArrayList<java.lang.String> codeBefore,private java.lang.Object console,private boolean consoleChecked,private boolean ready,private boolean running,private static volatile java.lang.Thread worker
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/PythonRunner.java
PythonRunner
doRunScript
class PythonRunner extends AbstractLocalFileScriptRunner { public static final String NAME = "Python"; public static final String TYPE = "text/python"; public static final String[] EXTENSIONS = new String[]{"py"}; @Override public String getName() { return NAME; } @Override public String[] getExtensions() { return EXTENSIONS; } @Override public String getType() { return TYPE; } public boolean isSupported() { // if (ExtensionManager.hasPython()) { // return true; // } return false; } @Override protected int doRunScript(String scriptfile, String[] scriptArgs, IRunner.Options options) {<FILL_FUNCTION_BODY>} }
if (!isSupported()) { return -1; } //TODO RunTime.startPythonServer(); String scriptContent = FileManager.readFileToString(new File(scriptfile)); Debug.log(3,"Python: running script: %s\n%s\n********** end", scriptfile, scriptContent); List<String> runArgs = new ArrayList<>(); runArgs.add(ExtensionManager.getPython()); runArgs.add(scriptfile); runArgs.addAll(Arrays.asList(scriptArgs)); String runOut = ProcessRunner.run(runArgs); int runExitValue = 0; if (!runOut.startsWith("0\n")) { Debug.error("%s", runOut); } else { Debug.logp("%s", runOut.substring(2)); } return 0;
208
217
425
<methods>public non-sealed void <init>() ,public boolean canHandle(java.lang.String) ,public void checkAndSetConsole() <variables>private static final Deque<java.lang.String> PREVIOUS_BUNDLE_PATHS
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/SikulixRunner.java
SikulixRunner
doRunScript
class SikulixRunner extends AbstractRunner { public static final String NAME = "Sikulix"; public static final String TYPE = "directory/sikulix"; private AbortableScriptRunnerWrapper wrapper = new AbortableScriptRunnerWrapper(); @Override public boolean isSupported() { return true; } @Override public String getName() { return NAME; } @Override public String[] getExtensions() { return new String[0]; } @Override public String getType() { return TYPE; } @Override public boolean canHandle(String identifier) { File file = new File(identifier); if (file.isDirectory()) { File innerScriptFile = Runner.getScriptFile(file); return null != innerScriptFile; } return false; } @Override protected int doRunScript(String scriptFolder, String[] scriptArgs, IRunner.Options options) {<FILL_FUNCTION_BODY>} public EffectiveRunner getEffectiveRunner(String scriptFileOrFolder) { File scriptFile = new File(scriptFileOrFolder); File innerScriptFile = Runner.getScriptFile(scriptFile); if (null != innerScriptFile) { String innerScriptFilePath = innerScriptFile.getAbsolutePath(); return new EffectiveRunner(Runner.getRunner(innerScriptFilePath), innerScriptFilePath, true); } return new EffectiveRunner(null, null, false); } @Override public boolean isAbortSupported() { return wrapper.isAbortSupported(); } @Override protected void doAbort() { wrapper.doAbort(); } }
EffectiveRunner runnerAndFile = getEffectiveRunner(scriptFolder); IRunner runner = runnerAndFile.getRunner(); String innerScriptFile = runnerAndFile.getScript(); if (null != runner) { try { wrapper.setRunner(runner); return runner.runScript(innerScriptFile, scriptArgs, options); } finally { wrapper.clearRunner(); } } return Runner.FILE_NOT_FOUND;
449
118
567
<methods>public non-sealed void <init>() ,public final void abort() ,public boolean canHandle(java.lang.String) ,public final boolean canHandleFileEnding(java.lang.String) ,public void checkAndSetConsole() ,public final void close() ,public boolean consoleChecked() ,public void consoleChecked(boolean) ,public final int evalScript(java.lang.String, org.sikuli.support.runner.IRunner.Options) ,public void execAfter(java.lang.String[]) ,public void execBefore(java.lang.String[]) ,public java.lang.String getDefaultExtension() ,public org.sikuli.support.runner.IRunner.EffectiveRunner getEffectiveRunner(java.lang.String) ,public java.lang.String[] getFileEndings() ,public final boolean hasExtension(java.lang.String) ,public final void init(java.lang.String[]) throws org.sikuli.script.SikuliXception,public boolean isAbortSupported() ,public final boolean isAborted() ,public final boolean isReady() ,public final boolean isRunning() ,public boolean isSupported() ,public final void redirect(java.io.PrintStream, java.io.PrintStream) ,public final void reset() ,public final void runLines(java.lang.String, org.sikuli.support.runner.IRunner.Options) ,public final int runScript(java.lang.String, java.lang.String[], org.sikuli.support.runner.IRunner.Options) ,public void setConsole(java.lang.Object) <variables>public static final int NOT_SUPPORTED,private static final java.util.concurrent.ScheduledExecutorService TIMEOUT_EXECUTOR,private static final java.lang.Object WORKER_LOCK,private boolean aborted,static ArrayList<java.lang.String> codeAfter,static ArrayList<java.lang.String> codeBefore,private java.lang.Object console,private boolean consoleChecked,private boolean ready,private boolean running,private static volatile java.lang.Thread worker
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/SikulixServer.java
TaskManager
request
class TaskManager { private LinkedHashMap<String, Task> allTasks; private LinkedBlockingDeque<Task> queue; private boolean shouldStop; private boolean shouldPause; private Object lock; private ExecutorService executor; public TaskManager() { allTasks = new LinkedHashMap<>(); queue = new LinkedBlockingDeque<>(); shouldStop = false; shouldPause = false; executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "Task Executor")); lock = new Object(); executor.execute(() -> { while (!shouldStop) { Task task = null; try { synchronized(lock) { while (shouldPause) { lock.wait(); } } task = queue.take(); if ("shouldStop".equals(task.id) || "shouldPause".equals(task.id)) { // NOOP } else { synchronized(task) { if (task.isWaiting()) { task.updateStatus(Task.Status.RUNNING); } } if (task.isRunning()) { task.runScript(); } } } catch (InterruptedException ex) { // NOOP } catch (Exception ex) { SikulixServer.dolog(-1, "ScriptExecutor: Exception: %s", ex); ex.printStackTrace(); if (task != null) { task.updateStatus(Task.Status.FAILED); } } finally { if (task != null) { synchronized(task) { task.notify(); } } } } }); } public Map<String, Task> getTasks(Optional<String> groupName, Optional<String> scriptName) { LinkedHashMap<String, Task> result = allTasks.entrySet().stream() .filter(e -> { if (groupName.isPresent()) { if (scriptName.isPresent()) { return groupName.get().equals(e.getValue().groupName) && scriptName.get().equals(e.getValue().scriptName); } else { return groupName.get().equals(e.getValue().groupName); } } else { if (scriptName.isPresent()) { return DEFAULT_GROUP.equals(e.getValue().groupName) && scriptName.get().equals(e.getValue().scriptName); } else { return true; } } }) .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (oldValue, newValue) -> newValue, LinkedHashMap::new)); return Collections.unmodifiableMap(result); } public Task requestSync(final String id, final String groupName, final String scriptName, final String[] scriptArgs) throws Exception { return request(id, groupName, scriptName, scriptArgs, false); } public Task requestAsync(final String id, final String groupName, final String scriptName, final String[] scriptArgs) throws Exception { return request(id, groupName, scriptName, scriptArgs, true); } private Task request(final String id, final String groupName, final String scriptName, final String[] scriptArgs, boolean isAsync) throws Exception {<FILL_FUNCTION_BODY>} public boolean cancel(final String id) { Task task = allTasks.get(id); if (task != null) { synchronized (task) { if (task.isWaiting()) { task.updateStatus(Task.Status.CANCELED); task.notify(); return true; } else { SikulixServer.dolog(-1, "could not cancel the task: %s", id); return false; } } } else { SikulixServer.dolog(-1, "the task is not found: %s", id); return false; } } public void stop() { shouldStop = true; queue.addFirst(new Task("shouldStop", null, null, null, true)); executor.shutdown(); while(!executor.isTerminated()) { try { executor.awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException ex) { ex.printStackTrace(); } } } public boolean pause() { synchronized(lock) { if (shouldPause) { return false; } else { shouldPause = true; queue.addFirst(new Task("shouldPause", null, null, null, true)); return true; } } } public boolean resume() { synchronized(lock) { if (shouldPause) { shouldPause = false; lock.notify(); return true; } else { return false; } } } public boolean isPaused() { return shouldPause; } }
Task request = new Task(id, groupName, scriptName, scriptArgs, isAsync); synchronized(allTasks) { allTasks.put(request.id, request); queue.put(request); } if (!isAsync) { synchronized(request) { while(request.isWaiting() || request.isRunning()) { request.wait(); } } } return request.clone();
1,283
113
1,396
<no_super_class>
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/SilkulixGitTestRunner.java
SilkulixGitTestRunner
doEvalScript
class SilkulixGitTestRunner extends NetworkRunner { public static final String NAME = "Git"; public static final String TYPE = "git"; public static final String[] EXTENSIONS = new String[0]; String GIT_SCRIPTS = "https://github.com/RaiMan/SikuliX-2014/tree/master/TestScripts/"; protected int doEvalScript(String scriptFile, IRunner.Options options) {<FILL_FUNCTION_BODY>} @Override public boolean isSupported() { return false; } @Override public String getName() { return NAME; } @Override public String[] getExtensions() { return EXTENSIONS.clone(); } @Override public String getType() { return TYPE; } }
if (scriptFile.endsWith(GIT_SCRIPTS)) { scriptFile = scriptFile + "showcase"; } return super.runScript(scriptFile, null, options);
230
54
284
<methods>public non-sealed void <init>() ,public boolean canHandle(java.lang.String) ,public java.lang.String[] getExtensions() ,public java.lang.String getName() ,public java.lang.String getType() ,public boolean isAbortSupported() ,public boolean isSupported() ,public java.lang.String resolveRelativeFile(java.lang.String) <variables>private org.sikuli.support.runner.AbortableScriptRunnerWrapper wrapper
RaiMan_SikuliX1
SikuliX1/IDE/src/main/java/org/sikuli/support/runner/ZipRunner.java
ZipRunner
getScriptEntry
class ZipRunner extends AbstractLocalFileScriptRunner { public static final String NAME = "PackedSikulix"; public static final String TYPE = "application/zip"; public static final String[] EXTENSIONS = new String[] { "zip" }; private AbortableScriptRunnerWrapper wrapper = new AbortableScriptRunnerWrapper(); @Override public boolean isSupported() { return true; } @Override public String getName() { return NAME; } @Override public String[] getExtensions() { return EXTENSIONS.clone(); } @Override public String getType() { return TYPE; } @Override public boolean canHandle(String identifier) { if (super.canHandle(identifier)) { try (ZipFile file = openZipFile(identifier)) { ZipEntry innerScriptFile = getScriptEntry(file); return null != innerScriptFile; } catch (IOException e) { log(-1, "Error opening file %s: %s", identifier, e.getMessage()); return false; } } return false; } public boolean hasTempBundle() { return true; } protected ZipFile openZipFile(String identifier) throws IOException { return new ZipFile(identifier); } protected String getScriptEntryName(ZipFile file) { return FilenameUtils.getBaseName(file.getName()); } @Override protected int doRunScript(String zipFile, String[] scriptArgs, IRunner.Options options) { EffectiveRunner runnerAndFile = getEffectiveRunner(zipFile); IRunner runner = runnerAndFile.getRunner(); String innerScriptFile = runnerAndFile.getScript(); try { if(null != innerScriptFile) { wrapper.setRunner(runner); return runner.runScript(innerScriptFile, scriptArgs, options); } return Runner.FILE_NOT_FOUND; } finally { wrapper.clearRunner(); if (null != innerScriptFile) { boolean success = FileManager.deleteFileOrFolder(new File(innerScriptFile).getParentFile()); if (!success) { log(-1, "Error deleting tmp dir %s", new File(innerScriptFile).getParentFile()); } } } } public EffectiveRunner getEffectiveRunner(String zipFile) { String innerScriptFilePath = null; try (ZipFile file = new ZipFile(zipFile)) { ZipEntry innerScriptFile = getScriptEntry(file); if(null != innerScriptFile) { File dir = extract(file); innerScriptFilePath = dir.getAbsolutePath() + File.separator + innerScriptFile.getName(); } } catch (IOException e) { log(-1, "Error opening file %s: %s", zipFile, e.getMessage()); } if (null != innerScriptFilePath) { return new EffectiveRunner(Runner.getRunner(innerScriptFilePath), innerScriptFilePath, null); } return new EffectiveRunner(); } private ZipEntry getScriptEntry(ZipFile file) {<FILL_FUNCTION_BODY>} private File extract(ZipFile jar) throws IOException { File dir = Files.createTempDirectory("sikulix").toFile(); Enumeration<? extends ZipEntry> entries = jar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File f = new File(dir.getAbsolutePath() + File.separator + entry.getName()); if (entry.isDirectory()) { f.mkdirs(); } else { try (InputStream is = jar.getInputStream(entry)) { try (FileOutputStream fo = new java.io.FileOutputStream(f)) { while (is.available() > 0) { fo.write(is.read()); } } } } } return dir; } @Override public boolean isAbortSupported() { return wrapper.isAbortSupported(); } @Override protected void doAbort() { wrapper.doAbort(); } }
Enumeration<? extends ZipEntry> entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (FilenameUtils.getBaseName(entry.getName()).equals(getScriptEntryName(file))) { for (IRunner runner : Runner.getRunners()) { if (runner.canHandle(entry.getName())) { return entry; } } } } return null;
1,095
127
1,222
<methods>public non-sealed void <init>() ,public boolean canHandle(java.lang.String) ,public void checkAndSetConsole() <variables>private static final Deque<java.lang.String> PREVIOUS_BUNDLE_PATHS
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/authentication/SecurityConfigurer.java
SecurityConfigurer
securityFilterChain
class SecurityConfigurer { @Autowired private RedisTemplate redisTemplate; @Autowired private AuthIgnoreConfig authIgnoreConfig; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>} // 解决跨域 public CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); source.registerCorsConfiguration("/**", corsConfiguration); return source; } @Bean public WebSecurityCustomizer webSecurityCustomizer() { // 开放静态资源权限 return web -> web.ignoring().antMatchers("/actuator/**", "/css/**", "/error"); } @Bean public CustomDaoAuthenticationProvider authenticationProvider() { CustomDaoAuthenticationProvider authenticationProvider = new CustomDaoAuthenticationProvider(); authenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder()); authenticationProvider.setUserDetailsService(userDetailsService()); return authenticationProvider; } @Bean public AuthenticationManager authenticationManager() { return new ProviderManager(Arrays.asList(authenticationProvider())); } @Bean public AuthenticationFailureHandler authenticationFailureHandler() { return new CustomAuthenticationFailHandler(); } @Bean public LogoutHandler logoutHandler() { return new CustomLogoutSuccessHandler(); } @Bean public AuthenticationSuccessHandler authenticationSuccessHandler() { return new CustomAuthenticationSuccessHandler(); } @Bean public UserDetailsService userDetailsService() { return new CustomUserDetailsService(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
List<String> permitAll = authIgnoreConfig.getIgnoreUrls(); permitAll.add("/error"); permitAll.add("/v3/**"); permitAll.add("/swagger-ui/**"); permitAll.add("/swagger-resources/**"); permitAll.add(Constant.TOKEN_ENTRY_POINT_URL); permitAll.add(Constant.TOKEN_LOGOUT_URL); String[] urls = permitAll.stream().distinct().toArray(String[]::new); // 基于 token,不需要 csrf http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.OPTIONS,"/**").permitAll(); // 跨域配置 http.cors().configurationSource(corsConfigurationSource()); // 基于 token,不需要 session http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 权限 http.authorizeRequests(authorize -> // 开放权限 authorize.antMatchers(urls).permitAll() // 其他地址的访问均需验证权限 .anyRequest().authenticated()); // 设置登录URL http.formLogin() .loginProcessingUrl(Constant.TOKEN_ENTRY_POINT_URL) .successHandler(authenticationSuccessHandler()) .failureHandler(authenticationFailureHandler()); // 设置退出URL http.logout() .logoutUrl(Constant.TOKEN_LOGOUT_URL) .logoutSuccessUrl("/sys/logout") .addLogoutHandler(logoutHandler()); // 如果不用验证码,注释这个过滤器即可 http.addFilterBefore(new ValidateCodeFilter(redisTemplate, authenticationFailureHandler()), UsernamePasswordAuthenticationFilter.class); // token 验证过滤器 http.addFilterBefore(new AuthenticationTokenFilter(authenticationManager(), authIgnoreConfig,redisTemplate), UsernamePasswordAuthenticationFilter.class); // 认证异常处理 http.exceptionHandling().authenticationEntryPoint(new TokenAuthenticationFailHandler()); // 用户管理service http.userDetailsService(userDetailsService()); return http.build();
507
555
1,062
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/authentication/detail/CustomUserDetailsService.java
CustomUserDetailsService
getDetail
class CustomUserDetailsService implements UserDetailsService { @Autowired private SysUserService sysUserService; // @Autowired // private PermissionsService permissionsService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username)); if (ObjectUtil.isNull(sysUser)) { throw new UsernameNotFoundException("用户不存在"); } return getDetail(sysUser); } public UserDetails loadUserByUserId(String userId) throws UsernameNotFoundException { SysUser sysUser = sysUserService.getById(userId); if (ObjectUtil.isNull(sysUser)) { throw new UsernameNotFoundException("用户不存在"); } return getDetail(sysUser); } private UserDetails getDetail(SysUser sysUser) {<FILL_FUNCTION_BODY>} }
// Set<String> permissions = permissionsService.getUserPermissions(sysUser.getUserId()); Set<String> permissions = new HashSet<>(); String[] roles = new String[0]; if (CollUtil.isNotEmpty(permissions)) { roles = permissions.stream().map(role -> "ROLE_" + role).toArray(String[]::new); } Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles); CustomUserDetailsUser customUserDetailsUser = new CustomUserDetailsUser(sysUser.getUserId(), sysUser.getUsername(), sysUser.getPassword(), authorities); return customUserDetailsUser;
267
168
435
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/authentication/handler/CustomAuthenticationFailHandler.java
CustomAuthenticationFailHandler
onAuthenticationFailure
class CustomAuthenticationFailHandler implements AuthenticationFailureHandler { private ObjectMapper objectMapper = new ObjectMapper(); @SneakyThrows @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception){<FILL_FUNCTION_BODY>} }
final String username = request.getParameter("username"); SysLoginLog loginLog = new SysLoginLog(); loginLog.setOptionIp(IPUtils.getIpAddr(request)); loginLog.setOptionName("用户登录失败"); loginLog.setOptionTerminal(request.getHeader("User-Agent")); loginLog.setUsername(username); SpringContextUtils.publishEvent(new LoginLogEvent(loginLog)); response.setCharacterEncoding(CharsetUtil.UTF_8); response.setContentType(MediaType.APPLICATION_JSON_VALUE); PrintWriter printWriter = response.getWriter(); printWriter.append(objectMapper.writeValueAsString(R.error(exception.getMessage())));
75
186
261
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/authentication/handler/CustomAuthenticationSuccessHandler.java
CustomAuthenticationSuccessHandler
onAuthenticationSuccess
class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Autowired private RedisTemplate redisTemplate; private ObjectMapper objectMapper = new ObjectMapper(); @SneakyThrows @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {<FILL_FUNCTION_BODY>} }
String token; String userId = ""; String userName = ""; if (authentication.getPrincipal() instanceof CustomUserDetailsUser) { CustomUserDetailsUser userDetailsUser = (CustomUserDetailsUser) authentication.getPrincipal(); token = SecureUtil.md5(userDetailsUser.getUsername() + System.currentTimeMillis()); userId = userDetailsUser.getUserId(); userName = userDetailsUser.getUsername(); } else { token = SecureUtil.md5(String.valueOf(System.currentTimeMillis())); } // 保存token redisTemplate.opsForValue().set(Constant.AUTHENTICATION_TOKEN + token, userId + "," + userName, Constant.TOKEN_EXPIRE, TimeUnit.SECONDS); log.info("用户ID:{},用户名:{},登录成功! token:{}", userId, userName, token); SysLoginLog loginLog = new SysLoginLog(); loginLog.setOptionIp(IPUtils.getIpAddr(request)); loginLog.setOptionName("用户登录成功"); loginLog.setOptionTerminal(request.getHeader("User-Agent")); loginLog.setUsername(userName); loginLog.setOptionTime(new Date()); SpringContextUtils.publishEvent(new LoginLogEvent(loginLog)); response.setCharacterEncoding(CharsetUtil.UTF_8); response.setContentType(MediaType.APPLICATION_JSON_VALUE); PrintWriter printWriter = response.getWriter(); printWriter.append(objectMapper.writeValueAsString(R.ok().put(Constant.TOKEN, token)));
92
425
517
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/authentication/handler/CustomLogoutSuccessHandler.java
CustomLogoutSuccessHandler
logout
class CustomLogoutSuccessHandler implements LogoutHandler { @Autowired private RedisTemplate redisTemplate; @SneakyThrows @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {<FILL_FUNCTION_BODY>} }
String token = request.getHeader(Constant.TOKEN); Object userInfo = redisTemplate.opsForValue().get(Constant.AUTHENTICATION_TOKEN + token); if (ObjectUtil.isNotNull(userInfo)) { String user[] = userInfo.toString().split(","); if (user != null && user.length == 2) { SysLoginLog loginLog = new SysLoginLog(); loginLog.setOptionIp(IPUtils.getIpAddr(request)); loginLog.setOptionName("用户退出成功"); loginLog.setOptionTerminal(request.getHeader("User-Agent")); loginLog.setUsername(user[1]); loginLog.setOptionTime(new Date()); SpringContextUtils.publishEvent(new LoginLogEvent(loginLog)); } } redisTemplate.delete(Constant.AUTHENTICATION_TOKEN + token);
78
231
309
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/authentication/handler/TokenAuthenticationFailHandler.java
TokenAuthenticationFailHandler
commence
class TokenAuthenticationFailHandler implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {<FILL_FUNCTION_BODY>} }
ObjectMapper objectMapper = new ObjectMapper(); response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); PrintWriter writer = response.getWriter(); writer.write(objectMapper.writeValueAsString(R.error(HttpStatus.UNAUTHORIZED.value(),authException.getMessage())));
57
99
156
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/authentication/provider/CustomDaoAuthenticationProvider.java
CustomDaoAuthenticationProvider
additionalAuthenticationChecks
class CustomDaoAuthenticationProvider extends DaoAuthenticationProvider { @Override public void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) {<FILL_FUNCTION_BODY>} }
if (authentication.getCredentials() == null) { throw new BadCredentialsException("认证错误"); } else { String presentedPassword = authentication.getCredentials().toString(); if (!this.getPasswordEncoder().matches(presentedPassword, userDetails.getPassword())) { throw new BadCredentialsException("帐号或密码错误"); } }
54
97
151
<methods>public void <init>() ,public void setPasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) ,public void setUserDetailsPasswordService(org.springframework.security.core.userdetails.UserDetailsPasswordService) ,public void setUserDetailsService(org.springframework.security.core.userdetails.UserDetailsService) <variables>private static final java.lang.String USER_NOT_FOUND_PASSWORD,private org.springframework.security.crypto.password.PasswordEncoder passwordEncoder,private org.springframework.security.core.userdetails.UserDetailsPasswordService userDetailsPasswordService,private org.springframework.security.core.userdetails.UserDetailsService userDetailsService,private volatile java.lang.String userNotFoundEncodedPassword
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/common/aspect/SysLogAspect.java
SysLogAspect
saveSysLog
class SysLogAspect { @Autowired private SysLogService sysLogService; private ObjectMapper objectMapper = new ObjectMapper(); @Pointcut("@annotation(com.suke.czx.common.annotation.SysLog)") public void logPointCut() { } @Around("logPointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { long beginTime = System.currentTimeMillis(); //执行方法 Object result = point.proceed(); //执行时长(毫秒) long time = System.currentTimeMillis() - beginTime; //保存日志 saveSysLog(point, time); return result; } @SneakyThrows private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {<FILL_FUNCTION_BODY>} }
MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLog sysLog = new SysLog(); com.suke.czx.common.annotation.SysLog syslog = method.getAnnotation(com.suke.czx.common.annotation.SysLog.class); if(syslog != null){ //注解上的描述 sysLog.setOperation(syslog.value()); } //请求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); //请求的参数 Object[] args = joinPoint.getArgs(); try{ String params = new Gson().toJson(args[0]); sysLog.setParams(params); }catch (Exception e){ } //获取request HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); //设置IP地址 sysLog.setIp(IPUtils.getIpAddr(request)); //用户名 // String username = ((CustomUserDetailsUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername(); 强转有问题...原因有待研究 String userStr = objectMapper.writeValueAsString(SecurityContextHolder.getContext().getAuthentication().getPrincipal()); HashMap<String,Object> userDetailsUser = objectMapper.readValue(userStr,HashMap.class); String username = MapUtil.getStr(userDetailsUser,"username"); sysLog.setUsername(username); sysLog.setTime(time); sysLog.setCreateDate(new Date()); //保存系统日志 sysLogService.save(sysLog);
230
467
697
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/common/utils/IPUtils.java
IPUtils
getIpAddr
class IPUtils { private static Logger logger = LoggerFactory.getLogger(IPUtils.class); /** * 获取IP地址 * * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 */ public static String getIpAddr(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
String ip = null; try { ip = request.getHeader("x-forwarded-for"); if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StrUtil.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } catch (Exception e) { logger.error("IPUtils ERROR ", e); } // //使用代理,则获取第一个IP地址 // if(StringUtils.isEmpty(ip) && ip.length() > 15) { // if(ip.indexOf(",") > 0) { // ip = ip.substring(0, ip.indexOf(",")); // } // } return ip;
157
351
508
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/common/utils/MPPageConvert.java
MPPageConvert
pageValueConvert
class MPPageConvert { public String getKeyword(Map<String, Object> param){ final String keyword = MapUtil.getStr(param, "keyword"); return keyword; } /** * @Author czx * @Description //TODO 前台传过来的参数转换为MyBatis Plus的Page * @Date 17:14 2019/4/18 * @Param [param] * @return com.baomidou.mybatisplus.core.metadata.IPage<T> **/ public <T> IPage<T> pageParamConvert(Map<String, Object> param){ int currPage = 1; int limit = 10; if(MapUtil.getInt(param,"current") != null){ currPage = MapUtil.getInt(param,"current"); } if(MapUtil.getInt(param,"limit") != null){ limit = MapUtil.getInt(param,"limit"); } IPage<T> page = new Page<>(currPage,limit); return page; } /** * @Author czx * @Description //TODO 将MyBatis Plus 的Page 转换为前台能用的Page * @Date 17:14 2019/4/18 * @Param [page] * @return java.util.HashMap **/ public HashMap pageValueConvert(IPage<?> page){<FILL_FUNCTION_BODY>} }
HashMap<Object,Object> pageData = new HashMap<>(); pageData.put("list",page.getRecords()); pageData.put("totalCount",page.getTotal()); pageData.put("limit",page.getSize()); pageData.put("current",page.getCurrent()); pageData.put("totalPage",page.getPages()); return pageData;
396
99
495
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/common/utils/UserUtil.java
UserUtil
getUser
class UserUtil { public CustomUserDetailsUser getUser() {<FILL_FUNCTION_BODY>} @SneakyThrows public String getUserId() { return getUser() == null ? null :getUser().getUserId(); } }
Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if(object != null){ return (CustomUserDetailsUser) object; } return null;
71
50
121
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/common/xss/SQLFilter.java
SQLFilter
sqlInject
class SQLFilter { /** * SQL注入过滤 * @param str 待验证的字符串 */ public static String sqlInject(String str){<FILL_FUNCTION_BODY>} }
if(StringUtils.isBlank(str)){ return null; } //去掉'|"|;|\字符 str = StringUtils.replace(str, "'", ""); str = StringUtils.replace(str, "\"", ""); str = StringUtils.replace(str, ";", ""); str = StringUtils.replace(str, "\\", ""); //转换成小写 str = str.toLowerCase(); //非法字符 String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "drop"}; //判断是否包含非法字符 for(String keyword : keywords){ if(str.indexOf(keyword) != -1){ throw new RRException("包含非法字符"); } } return str;
61
222
283
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/common/xss/XssHttpServletRequestWrapper.java
XssHttpServletRequestWrapper
getInputStream
class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { //没被包装过的HttpServletRequest(特殊场景,需要自己过滤) HttpServletRequest orgRequest; //html过滤 private final static HTMLFilter htmlFilter = new HTMLFilter(); public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); orgRequest = request; } @Override public ServletInputStream getInputStream() throws IOException {<FILL_FUNCTION_BODY>} @Override public String getParameter(String name) { String value = super.getParameter(xssEncode(name)); if (StringUtils.isNotBlank(value)) { value = xssEncode(value); } return value; } @Override public String[] getParameterValues(String name) { String[] parameters = super.getParameterValues(name); if (parameters == null || parameters.length == 0) { return null; } for (int i = 0; i < parameters.length; i++) { parameters[i] = xssEncode(parameters[i]); } return parameters; } @Override public Map<String, String[]> getParameterMap() { Map<String, String[]> map = new LinkedHashMap<>(); Map<String, String[]> parameters = super.getParameterMap(); for (String key : parameters.keySet()) { String[] values = parameters.get(key); for (int i = 0; i < values.length; i++) { values[i] = xssEncode(values[i]); } map.put(key, values); } return map; } @Override public String getHeader(String name) { String value = super.getHeader(xssEncode(name)); if (StringUtils.isNotBlank(value)) { value = xssEncode(value); } return value; } private String xssEncode(String input) { return htmlFilter.filter(input); } /** * 获取最原始的request */ public HttpServletRequest getOrgRequest() { return orgRequest; } /** * 获取最原始的request */ public static HttpServletRequest getOrgRequest(HttpServletRequest request) { if (request instanceof XssHttpServletRequestWrapper) { return ((XssHttpServletRequestWrapper) request).getOrgRequest(); } return request; } }
//非json类型,直接返回 if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))) { return super.getInputStream(); } //为空,直接返回 String json = IOUtils.toString(super.getInputStream(), "utf-8"); if (StringUtils.isBlank(json)) { return super.getInputStream(); } //xss过滤 final XssIgnoreConfig xssIgnoreConfig = SpringContextUtils.getBean(XssIgnoreConfig.class); final String requestURI = orgRequest.getRequestURI(); if (xssIgnoreConfig == null || !xssIgnoreConfig.isContains(requestURI)) { json = xssEncode(json); } final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8")); return new ServletInputStream() { @Override public boolean isFinished() { return true; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener readListener) { } @Override public int read() throws IOException { return bis.read(); } };
652
322
974
<methods>public void <init>(javax.servlet.http.HttpServletRequest) ,public boolean authenticate(javax.servlet.http.HttpServletResponse) throws java.io.IOException, javax.servlet.ServletException,public java.lang.String changeSessionId() ,public java.lang.String getAuthType() ,public java.lang.String getContextPath() ,public javax.servlet.http.Cookie[] getCookies() ,public long getDateHeader(java.lang.String) ,public java.lang.String getHeader(java.lang.String) ,public Enumeration<java.lang.String> getHeaderNames() ,public Enumeration<java.lang.String> getHeaders(java.lang.String) ,public javax.servlet.http.HttpServletMapping getHttpServletMapping() ,public int getIntHeader(java.lang.String) ,public java.lang.String getMethod() ,public javax.servlet.http.Part getPart(java.lang.String) throws java.io.IOException, javax.servlet.ServletException,public Collection<javax.servlet.http.Part> getParts() throws java.io.IOException, javax.servlet.ServletException,public java.lang.String getPathInfo() ,public java.lang.String getPathTranslated() ,public java.lang.String getQueryString() ,public java.lang.String getRemoteUser() ,public java.lang.String getRequestURI() ,public java.lang.StringBuffer getRequestURL() ,public java.lang.String getRequestedSessionId() ,public java.lang.String getServletPath() ,public javax.servlet.http.HttpSession getSession() ,public javax.servlet.http.HttpSession getSession(boolean) ,public Map<java.lang.String,java.lang.String> getTrailerFields() ,public java.security.Principal getUserPrincipal() ,public boolean isRequestedSessionIdFromCookie() ,public boolean isRequestedSessionIdFromURL() ,public boolean isRequestedSessionIdFromUrl() ,public boolean isRequestedSessionIdValid() ,public boolean isTrailerFieldsReady() ,public boolean isUserInRole(java.lang.String) ,public void login(java.lang.String, java.lang.String) throws javax.servlet.ServletException,public void logout() throws javax.servlet.ServletException,public javax.servlet.http.PushBuilder newPushBuilder() ,public T upgrade(Class<T>) throws java.io.IOException, javax.servlet.ServletException<variables>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/config/AuthIgnoreConfig.java
AuthIgnoreConfig
afterPropertiesSet
class AuthIgnoreConfig implements InitializingBean { @Autowired private WebApplicationContext applicationContext; private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}"); private static final String ASTERISK = "*"; @Getter @Setter private List<String> ignoreUrls = new ArrayList<>(); @Override public void afterPropertiesSet(){<FILL_FUNCTION_BODY>} public boolean isContains(String url){ final String u = ReUtil.replaceAll(url, PATTERN, ASTERISK); return ignoreUrls.contains(u); } }
RequestMappingHandlerMapping mapping = applicationContext.getBean("requestMappingHandlerMapping",RequestMappingHandlerMapping.class); Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods(); map.keySet().forEach(mappingInfo -> { HandlerMethod handlerMethod = map.get(mappingInfo); AuthIgnore method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), AuthIgnore.class); if(method != null){ PatternsRequestCondition patternsCondition = mappingInfo.getPatternsCondition(); if(patternsCondition != null){ patternsCondition.getPatterns().stream().forEach(url ->{ ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, ASTERISK)); }); } } });
165
193
358
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/config/FilterConfig.java
FilterConfig
xssFilterRegistration
class FilterConfig { @Bean public FilterRegistrationBean xssFilterRegistration() {<FILL_FUNCTION_BODY>} }
FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setDispatcherTypes(DispatcherType.REQUEST); registration.setFilter(new XssFilter()); registration.addUrlPatterns("/*"); registration.setName("xssFilter"); registration.setOrder(Integer.MAX_VALUE); return registration;
39
84
123
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/config/KaptchaConfig.java
KaptchaConfig
producer
class KaptchaConfig { @Bean public DefaultKaptcha producer() {<FILL_FUNCTION_BODY>} }
Properties properties = new Properties(); properties.put("kaptcha.border", "no"); properties.put("kaptcha.textproducer.font.color", "black"); properties.put("kaptcha.textproducer.char.space", "5"); Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha;
36
115
151
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/config/MyBatisPlusConfig.java
MyBatisPlusConfig
mybatisPlusInterceptor
class MyBatisPlusConfig { /** * 新的分页插件,一缓和二缓遵循mybatis的规则 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>} }
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); //向Mybatis过滤器链中添加分页拦截器 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); //还可以添加i他的拦截器 return interceptor;
75
89
164
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/config/SwaggerConfig.java
SwaggerConfig
springfoxHandlerProviderBeanPostProcessor
class SwaggerConfig { @Autowired private SwaggerProperties swaggerProperties; /** * 通过 createRestApi函数来构建一个DocketBean * 函数名,可以随意命名,喜欢什么命名就什么命名 */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30) .pathMapping("/") .enable(swaggerProperties.getEnable())//生产禁用 .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))//方法一、扫描类上有@Api的,推荐,不会显示basic-error-controller // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//方法二、扫描方法上有@ApiOperation,但缺少类信息,不会显示basic-error-controller // .apis(RequestHandlerSelectors.basePackage("com.suke.czx.modules"))//按包扫描,也可以扫描共同的父包,不会显示basic-error-controller // .paths(PathSelectors.regex("/.*"))// 对根下所有路径进行监控 .paths(PathSelectors.any()) .build(); } /** * API 页面上半部分展示信息 */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(swaggerProperties.getTitle())//标题 .description(swaggerProperties.getDescription())//描述 .contact(new Contact(swaggerProperties.getAuthor(), swaggerProperties.getUrl(), swaggerProperties.getEmail()))//作者信息 .version(swaggerProperties.getVersion())//版本号 .build(); } /** * 解决springboot 2.7.7 的security 报错问题 */ @Bean public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {<FILL_FUNCTION_BODY>} }
return new BeanPostProcessor() { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) { customizeSpringfoxHandlerMappings(getHandlerMappings(bean)); } return bean; } private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) { List<T> copy = mappings.stream() .filter(mapping -> mapping.getPatternParser() == null) .collect(Collectors.toList()); mappings.clear(); mappings.addAll(copy); } @SuppressWarnings("unchecked") private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) { try { Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings"); field.setAccessible(true); return (List<RequestMappingInfoHandlerMapping>) field.get(bean); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } } };
502
306
808
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/config/XssIgnoreConfig.java
XssIgnoreConfig
afterPropertiesSet
class XssIgnoreConfig implements InitializingBean { @Autowired private WebApplicationContext applicationContext; private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}"); private static final String ASTERISK = "*"; @Getter @Setter private List<String> ignoreUrls = new ArrayList<>(); @Override public void afterPropertiesSet(){<FILL_FUNCTION_BODY>} public boolean isContains(String url){ final String u = ReUtil.replaceAll(url, PATTERN, ASTERISK); return ignoreUrls.contains(u); } }
RequestMappingHandlerMapping mapping = applicationContext.getBean("requestMappingHandlerMapping",RequestMappingHandlerMapping.class); Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods(); map.keySet().forEach(mappingInfo -> { HandlerMethod handlerMethod = map.get(mappingInfo); XssIgnore method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), XssIgnore.class); if(method != null){ mappingInfo.getPathPatternsCondition().getPatternValues().stream().forEach(url ->{ ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, ASTERISK)); }); } });
166
170
336
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/interceptor/AuthenticationTokenFilter.java
AuthenticationTokenFilter
doFilterInternal
class AuthenticationTokenFilter extends BasicAuthenticationFilter { private RedisTemplate redisTemplate; private AuthIgnoreConfig authIgnoreConfig; private ObjectMapper objectMapper = new ObjectMapper(); public AuthenticationTokenFilter(AuthenticationManager authenticationManager, AuthIgnoreConfig authIgnoreConfig,RedisTemplate template) { super(authenticationManager); this.redisTemplate = template; this.authIgnoreConfig = authIgnoreConfig; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>} @SneakyThrows public void writer(HttpServletResponse response, String msg) { response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write(objectMapper.writeValueAsString(R.error(HttpServletResponse.SC_UNAUTHORIZED, msg))); } }
String token = request.getHeader(Constant.TOKEN); if (StrUtil.isBlank(token) || StrUtil.equals(token, "null")) { token = request.getParameter(Constant.TOKEN); } if (StrUtil.isNotBlank(token) && !StrUtil.equals(token, "null")) { final String requestURI = request.getRequestURI(); if(!authIgnoreConfig.isContains(requestURI)){ Object userInfo = redisTemplate.opsForValue().get(Constant.AUTHENTICATION_TOKEN + token); if (ObjectUtil.isNull(userInfo)) { writer(response, "无效token"); return; } String user[] = userInfo.toString().split(","); if (user == null || user.length != 2) { writer(response, "无效token"); return; } String userId = user[0]; CustomUserDetailsService customUserDetailsService = SpringContextUtils.getBean(CustomUserDetailsService.class); UserDetails userDetails = customUserDetailsService.loadUserByUserId(userId); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } chain.doFilter(request, response);
250
362
612
<methods>public void <init>(org.springframework.security.authentication.AuthenticationManager) ,public void <init>(org.springframework.security.authentication.AuthenticationManager, org.springframework.security.web.AuthenticationEntryPoint) ,public void afterPropertiesSet() ,public void setAuthenticationDetailsSource(AuthenticationDetailsSource<javax.servlet.http.HttpServletRequest,?>) ,public void setCredentialsCharset(java.lang.String) ,public void setRememberMeServices(org.springframework.security.web.authentication.RememberMeServices) ,public void setSecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository) <variables>private org.springframework.security.web.authentication.www.BasicAuthenticationConverter authenticationConverter,private org.springframework.security.web.AuthenticationEntryPoint authenticationEntryPoint,private org.springframework.security.authentication.AuthenticationManager authenticationManager,private java.lang.String credentialsCharset,private boolean ignoreFailure,private org.springframework.security.web.authentication.RememberMeServices rememberMeServices,private org.springframework.security.web.context.SecurityContextRepository securityContextRepository
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/interceptor/ValidateCodeFilter.java
ValidateCodeFilter
doFilterInternal
class ValidateCodeFilter extends OncePerRequestFilter { private AntPathMatcher pathMatcher = new AntPathMatcher(); private RedisTemplate redisTemplate; private AuthenticationFailureHandler authenticationFailureHandler; public ValidateCodeFilter(RedisTemplate redisTemplate, AuthenticationFailureHandler authenticationFailureHandler){ this.redisTemplate = redisTemplate; this.authenticationFailureHandler = authenticationFailureHandler; } @SneakyThrows @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {<FILL_FUNCTION_BODY>} }
String url = request.getRequestURI(); if (pathMatcher.match(Constant.TOKEN_ENTRY_POINT_URL,url)){ String captcha = request.getParameter("captcha"); String randomStr = request.getParameter("randomStr"); if(StrUtil.isBlank(captcha) || StrUtil.isBlank(randomStr)){ CustomAuthenticationException exception = new CustomAuthenticationException("验证码为空"); authenticationFailureHandler.onAuthenticationFailure(request,response,exception); return; } String code_key = (String) redisTemplate.opsForValue().get(Constant.NUMBER_CODE_KEY + randomStr); if(StrUtil.isEmpty(code_key)){ CustomAuthenticationException exception = new CustomAuthenticationException("验证码过期"); authenticationFailureHandler.onAuthenticationFailure(request,response,exception); return; } if(!captcha.equalsIgnoreCase(code_key)){ CustomAuthenticationException exception = new CustomAuthenticationException("验证码不正确"); authenticationFailureHandler.onAuthenticationFailure(request,response,exception); return; } } filterChain.doFilter(request,response);
154
294
448
<methods>public void <init>() ,public final void doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) throws javax.servlet.ServletException, java.io.IOException<variables>public static final java.lang.String ALREADY_FILTERED_SUFFIX
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/apk/controller/TbApkVersionController.java
TbApkVersionController
list
class TbApkVersionController extends AbstractController { private final TbApkVersionService tbApkVersionService; /** * 列表 */ @ApiOperation(value = "APK版本管理列表") @GetMapping("/list") public R list(@RequestParam Map<String, Object> params) {<FILL_FUNCTION_BODY>} /** * 新增APK版本管理 */ @ApiOperation(value = "新增APK版本管理数据") @SysLog("新增APK版本管理数据") @PostMapping("/save") public R save(@RequestBody TbApkVersion param) { param.setCreateTime(new Date()); param.setUserId(getUserId()); tbApkVersionService.save(param); return R.ok(); } /** * 删除 */ @ApiOperation(value = "删除APK版本管理数据") @SysLog("删除APK版本管理数据") @PostMapping("/delete") public R delete(@RequestBody TbApkVersion param) { if(param.getId() == null){ return R.error("ID为空"); } tbApkVersionService.removeById(param.getId()); return R.ok(); } }
//查询列表数据 QueryWrapper<TbApkVersion> queryWrapper = new QueryWrapper<>(); final String keyword = mpPageConvert.getKeyword(params); if (StrUtil.isNotEmpty(keyword)) { queryWrapper.lambda().and(func -> func.like(TbApkVersion::getUpdateContent,keyword)); } queryWrapper.lambda().orderByDesc(TbApkVersion::getCreateTime); IPage<TbApkVersion> listPage = tbApkVersionService.page(mpPageConvert.<TbApkVersion>pageParamConvert(params), queryWrapper); return R.ok().setData(listPage);
335
168
503
<methods>public non-sealed void <init>() <variables>protected com.suke.czx.common.utils.MPPageConvert mpPageConvert,public com.fasterxml.jackson.databind.ObjectMapper objectMapper
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/gen/controller/SysGenController.java
SysGenController
list
class SysGenController extends AbstractController { private final SysGenService sysGenService; /** * 列表 */ @GetMapping(value = "/list") public R list(@RequestParam Map<String, Object> params) {<FILL_FUNCTION_BODY>} /** * 生成代码 * * @param makerConfigEntity */ @PostMapping(value = "/create") public R create(@RequestBody MakerConfigEntity makerConfigEntity) { sysGenService.generatorCode(makerConfigEntity); return R.ok(); } }
//查询列表数据 QueryWrapper<InfoRmationSchema> queryWrapper = new QueryWrapper<>(); final String keyword = mpPageConvert.getKeyword(params); if (StrUtil.isNotEmpty(keyword)) { queryWrapper .lambda() .like(InfoRmationSchema::getTableName, keyword); } IPage<InfoRmationSchema> pageList = sysGenService.queryTableList(mpPageConvert.<InfoRmationSchema>pageParamConvert(params), queryWrapper); return R.ok().setData(pageList);
155
140
295
<methods>public non-sealed void <init>() <variables>protected com.suke.czx.common.utils.MPPageConvert mpPageConvert,public com.fasterxml.jackson.databind.ObjectMapper objectMapper
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/gen/service/impl/SysGenServiceImpl.java
SysGenServiceImpl
generatorCode
class SysGenServiceImpl extends ServiceImpl<SysGenMapper, InfoRmationSchema> implements SysGenService { private final SysGenMapper sysGenMapper; private final GenUtils genUtils; @Override public IPage<InfoRmationSchema> queryTableList(IPage page, QueryWrapper<InfoRmationSchema> entityWrapper) { return sysGenMapper.queryTableList(page, entityWrapper); } @Override public void generatorCode(MakerConfigEntity config) {<FILL_FUNCTION_BODY>} }
//查询表信息 InfoRmationSchema table = sysGenMapper.queryTableList(new QueryWrapper<InfoRmationSchema>().eq("tableName", config.getTableName())); //查询列信息 List<ColumnEntity> columns = sysGenMapper.queryColumns(new QueryWrapper<ColumnEntity>().eq("tableName", config.getTableName())); //生成代码 genUtils.maker(config, table, columns);
137
109
246
<methods>public void <init>() ,public com.suke.czx.modules.gen.mapper.SysGenMapper getBaseMapper() ,public Class<com.suke.czx.modules.gen.entity.InfoRmationSchema> getEntityClass() ,public Map<java.lang.String,java.lang.Object> getMap(Wrapper<com.suke.czx.modules.gen.entity.InfoRmationSchema>) ,public V getObj(Wrapper<com.suke.czx.modules.gen.entity.InfoRmationSchema>, Function<? super java.lang.Object,V>) ,public com.suke.czx.modules.gen.entity.InfoRmationSchema getOne(Wrapper<com.suke.czx.modules.gen.entity.InfoRmationSchema>, boolean) ,public Optional<com.suke.czx.modules.gen.entity.InfoRmationSchema> getOneOpt(Wrapper<com.suke.czx.modules.gen.entity.InfoRmationSchema>, boolean) ,public boolean removeBatchByIds(Collection<?>, int) ,public boolean removeBatchByIds(Collection<?>, int, boolean) ,public boolean removeById(java.io.Serializable) ,public boolean removeById(java.io.Serializable, boolean) ,public boolean removeByIds(Collection<?>) ,public boolean saveBatch(Collection<com.suke.czx.modules.gen.entity.InfoRmationSchema>, int) ,public boolean saveOrUpdate(com.suke.czx.modules.gen.entity.InfoRmationSchema) ,public boolean saveOrUpdateBatch(Collection<com.suke.czx.modules.gen.entity.InfoRmationSchema>, int) ,public boolean updateBatchById(Collection<com.suke.czx.modules.gen.entity.InfoRmationSchema>, int) <variables>protected com.suke.czx.modules.gen.mapper.SysGenMapper baseMapper,protected Class<com.suke.czx.modules.gen.entity.InfoRmationSchema> entityClass,protected org.apache.ibatis.logging.Log log,protected Class<com.suke.czx.modules.gen.mapper.SysGenMapper> mapperClass,protected org.apache.ibatis.session.SqlSessionFactory sqlSessionFactory,protected final Class<?>[] typeArguments
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/oss/cloud/QiniuCloudStorageService.java
QiniuCloudStorageService
upload
class QiniuCloudStorageService implements ICloudStorage { private final Auth auth; private final UploadManager uploadManager; private final QiniuProperties qiniuProperties; @Override public String upload(byte[] data, String path) {<FILL_FUNCTION_BODY>} @Override public String upload(InputStream inputStream, String path) { try { byte[] data = IOUtils.toByteArray(inputStream); return this.upload(data, path); } catch (IOException e) { throw new RRException("上传文件失败", e); } } @Override public String uploadSuffix(byte[] data, String suffix) { return upload(data, getPath(qiniuProperties.getPrefix(), suffix)); } @Override public String uploadSuffix(InputStream inputStream, String suffix) { return upload(inputStream, getPath(qiniuProperties.getPrefix(), suffix)); } }
try { String token = auth.uploadToken(qiniuProperties.getBucketName()); Response res = uploadManager.put(data, path, token); if (!res.isOK()) { throw new RRException("上传七牛出错:" + res.getInfo()); } } catch (Exception e) { throw new RRException("上传文件失败,请核对七牛配置信息", e); } return qiniuProperties.getDomain() + "/" + path;
249
134
383
<no_super_class>
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/oss/controller/SysOssController.java
SysOssController
uploadApk
class SysOssController extends AbstractController { private final SysOssService sysOssService; private final ICloudStorage iCloudStorage; /** * 列表 */ @GetMapping(value = "/list") public R list(@RequestParam Map<String, Object> params) { //查询列表数据 QueryWrapper<SysOss> queryWrapper = new QueryWrapper<>(); IPage<SysOss> pageList = sysOssService.page(mpPageConvert.<SysOss>pageParamConvert(params), queryWrapper); return R.ok().setData(pageList); } /** * 上传文件 */ @PostMapping(value = "/upload") public R upload(@RequestParam("file") MultipartFile file) throws Exception { if (file.isEmpty()) { throw new RRException("上传文件不能为空"); } //上传文件 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String url = ""; //保存文件信息 SysOss ossEntity = new SysOss(); ossEntity.setUrl(url); ossEntity.setCreateDate(new Date()); sysOssService.save(ossEntity); return R.ok().put("url", url); } /** * 上传文件 */ @AuthIgnore @PostMapping(value = "/upload/apk") public R uploadApk(@RequestParam("file") MultipartFile file) {<FILL_FUNCTION_BODY>} /** * 删除 */ @PostMapping(value = "/delete") public R delete(@RequestBody Long[] ids) { sysOssService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
if (file.isEmpty()) { return R.error("上传文件不能为空"); } // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件后缀 String prefix = fileName.substring(fileName.lastIndexOf(".")); if (prefix == null || !prefix.equals(".apk")) { return R.error("只能上传APK文件"); } TbApkVersion apkVersion = null; File tempFile = new File(fileName); try { FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); ApkFile apkFile = new ApkFile(tempFile); ApkMeta apkMeta = apkFile.getApkMeta(); apkVersion = new TbApkVersion(); apkVersion.setVersionCode(Math.toIntExact(apkMeta.getVersionCode())); apkVersion.setVersionName(apkMeta.getVersionName()); apkVersion.setAppName(apkMeta.getLabel()); apkVersion.setPackageName(apkMeta.getPackageName()); apkVersion.setFileName(file.getOriginalFilename()); apkVersion.setMd5Value(DigestUtil.md5Hex(tempFile)); apkVersion.setFileSize(String.valueOf(tempFile.length())); //上传文件 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String url = iCloudStorage.uploadSuffix(file.getBytes(), suffix); //保存文件信息 SysOss ossEntity = new SysOss(); ossEntity.setUrl(url); ossEntity.setCreateDate(new Date()); sysOssService.save(ossEntity); apkVersion.setDownloadUrl(url); } catch (Exception e) { log.error("文件上传失败:{}", e.getMessage()); return R.error("文件上传失败"); } tempFile.delete(); return R.ok().setData(apkVersion);
483
537
1,020
<methods>public non-sealed void <init>() <variables>protected com.suke.czx.common.utils.MPPageConvert mpPageConvert,public com.fasterxml.jackson.databind.ObjectMapper objectMapper
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/sys/controller/SysLogController.java
SysLogController
loginList
class SysLogController extends AbstractController { private final SysLogService sysLogService; private final SysLoginLogService sysLoginLogService; /** * 列表 */ @GetMapping(value = "/list") public R list(@RequestParam Map<String, Object> params) { //查询列表数据 QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>(); final String keyword = mpPageConvert.getKeyword(params); if (StrUtil.isNotEmpty(keyword)) { queryWrapper .lambda() .like(SysLog::getUsername, keyword) .or() .like(SysLog::getOperation, keyword); } queryWrapper.lambda().orderByDesc(SysLog::getCreateDate); IPage<SysLog> listPage = sysLogService.page(mpPageConvert.<SysLog>pageParamConvert(params), queryWrapper); return R.ok().setData(listPage); } /** * 列表 */ @GetMapping(value = "/loginList") public R loginList(@RequestParam Map<String, Object> params) {<FILL_FUNCTION_BODY>} }
//查询列表数据 QueryWrapper<SysLoginLog> queryWrapper = new QueryWrapper<>(); final String keyword = mpPageConvert.getKeyword(params); if (StrUtil.isNotEmpty(keyword)) { queryWrapper .lambda() .like(SysLoginLog::getUsername, keyword) .or() .like(SysLoginLog::getOptionName, keyword); } queryWrapper.lambda().orderByDesc(SysLoginLog::getOptionTime); IPage<SysLoginLog> listPage = sysLoginLogService.page(mpPageConvert.<SysLoginLog>pageParamConvert(params), queryWrapper); return R.ok().setData(listPage);
307
180
487
<methods>public non-sealed void <init>() <variables>protected com.suke.czx.common.utils.MPPageConvert mpPageConvert,public com.fasterxml.jackson.databind.ObjectMapper objectMapper
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/sys/controller/SysLoginController.java
SysLoginController
captcha
class SysLoginController extends AbstractController { private final Producer producer; private final RedisTemplate redisTemplate; @AuthIgnore @RequestMapping(value = "/", method = RequestMethod.GET) public R hello() { return R.ok("hello welcome to use x-springboot"); } /** * 验证码 */ @AuthIgnore @SneakyThrows @RequestMapping(value = "/sys/code/{time}", method = RequestMethod.GET) public void captcha(@PathVariable("time") String time, HttpServletResponse response) {<FILL_FUNCTION_BODY>} /** * 退出 */ @AuthIgnore @GetMapping(value = "/sys/logout") public void logout() { } }
response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); //生成文字验证码 String text = producer.createText(); log.info("验证码:{}", text); //生成图片验证码 BufferedImage image = producer.createImage(text); //redis 60秒 redisTemplate.opsForValue().set(Constant.NUMBER_CODE_KEY + time, text, 60, TimeUnit.SECONDS); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); IoUtil.close(out);
209
174
383
<methods>public non-sealed void <init>() <variables>protected com.suke.czx.common.utils.MPPageConvert mpPageConvert,public com.fasterxml.jackson.databind.ObjectMapper objectMapper
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/sys/controller/SysMenuController.java
SysMenuController
delete
class SysMenuController extends AbstractController { private final SysMenuNewService sysMenuNewService; /** * 所有菜单列表 */ @GetMapping(value = "/list") public R list(@RequestParam Map<String, Object> params) { final List<SysMenuNewVO> userMenu = sysMenuNewService.getUserMenu(); return R.ok().setData(userMenu); } /** * 保存 */ @SysLog("保存菜单") @PostMapping(value = "/save") public R save(@RequestBody SysMenuNewVO menu) { SysMenuNew menuNew = this.getParam(menu); if(menuNew.getParentId() == null){ menuNew.setParentId(0L); } sysMenuNewService.save(menuNew); return R.ok(); } /** * 修改 */ @SysLog("修改菜单") @PostMapping(value = "/update") public R update(@RequestBody SysMenuNewVO menu) { if (menu.getMenuId() == null) { return R.error("菜单ID为空"); } SysMenuNew menuNew = this.getParam(menu); menuNew.setMenuId(menu.getMenuId()); sysMenuNewService.updateById(menuNew); return R.ok(); } public SysMenuNew getParam(SysMenuNewVO menu) { SysMenuNew menuNew = new SysMenuNew(); menuNew.setParentId(menu.getParentId()); menuNew.setPath(menu.getPath()); menuNew.setName(menu.getName()); menuNew.setComponent(menu.getComponent()); menuNew.setRedirect(menu.getRedirect()); menuNew.setTitle(menu.getTitle()); menuNew.setOrderSort(menu.getOrderSort()); if (menu.getMeta() != null) { menuNew.setTitle(menu.getMeta().getTitle()); menuNew.setIsLink(menu.getMeta().getIsLink()); menuNew.setHide(menu.getMeta().isHide()); menuNew.setKeepAlive(menu.getMeta().isKeepAlive()); menuNew.setAffix(menu.getMeta().isAffix()); menuNew.setIframe(menu.getMeta().isIframe()); menuNew.setIcon(menu.getMeta().getIcon()); menuNew.setRoles(menu.getMeta().getRoles()); menuNew.setDisabled(!menu.getMeta().isHide()); } return menuNew; } /** * 删除 */ @SysLog("删除菜单") @PostMapping(value = "/delete") public R delete(@RequestBody SysMenuNew menu) {<FILL_FUNCTION_BODY>} }
if (menu == null) { return R.error("参数错误"); } Long menuId = menu.getMenuId(); if (menuId == null) { return R.error("ID为空"); } //判断是否有子菜单或按钮 QueryWrapper<SysMenuNew> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(SysMenuNew::getParentId, menuId); List<SysMenuNew> menuList = sysMenuNewService.list(queryWrapper); if (menuList.size() > 0) { return R.error("请先删除子菜单"); } sysMenuNewService.removeById(menuId); return R.ok();
746
186
932
<methods>public non-sealed void <init>() <variables>protected com.suke.czx.common.utils.MPPageConvert mpPageConvert,public com.fasterxml.jackson.databind.ObjectMapper objectMapper
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/sys/controller/SysRoleController.java
SysRoleController
list
class SysRoleController extends AbstractController { private final SysRoleService sysRoleService; /** * 角色列表 */ @AutoFullData @GetMapping(value = "/list") public R list(@RequestParam Map<String, Object> params) {<FILL_FUNCTION_BODY>} /** * 角色列表 */ @GetMapping(value = "/select") public R select() { final List<SysRole> list = sysRoleService.list(); return R.ok().setData(list); } /** * 保存角色 */ @SysLog("保存角色") @PostMapping(value = "/save") public R save(@RequestBody SysRole role) { role.setCreateUserId(getUserId()); sysRoleService.saveRoleMenu(role); return R.ok(); } /** * 修改角色 */ @SysLog("修改角色") @PostMapping(value = "/update") public R update(@RequestBody SysRole role) { role.setCreateUserId(getUserId()); sysRoleService.updateRoleMenu(role); return R.ok(); } /** * 删除角色 */ @SysLog("删除角色") @PostMapping(value = "/delete") public R delete(@RequestBody SysRole role) { if (role == null || role.getRoleId() == null) { return R.error("ID为空"); } sysRoleService.deleteBath(role.getRoleId()); return R.ok(); } }
QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>(); //如果不是超级管理员,则只查询自己创建的角色列表 if (!getUserId().equals(Constant.SUPER_ADMIN)) { queryWrapper.lambda().eq(SysRole::getCreateUserId, getUserId()); } //查询列表数据 final String keyword = mpPageConvert.getKeyword(params); if (StrUtil.isNotEmpty(keyword)) { queryWrapper .lambda() .and(func -> func.like(SysRole::getRoleName, keyword)); } IPage<SysRole> listPage = sysRoleService.page(mpPageConvert.<SysRole>pageParamConvert(params), queryWrapper); return R.ok().setData(listPage);
429
206
635
<methods>public non-sealed void <init>() <variables>protected com.suke.czx.common.utils.MPPageConvert mpPageConvert,public com.fasterxml.jackson.databind.ObjectMapper objectMapper
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/sys/controller/SysUserController.java
SysUserController
sysInfo
class SysUserController extends AbstractController { private final SysUserService sysUserService; private final PasswordEncoder passwordEncoder; private final SysMenuNewService sysMenuNewService; /** * 所有用户列表 */ @AutoFullData @GetMapping(value = "/list") public R list(@RequestParam Map<String, Object> params) { //查询列表数据 QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>(); //只有超级管理员,才能查看所有管理员列表 if (!getUserId().equals(Constant.SUPER_ADMIN)) { queryWrapper.lambda().eq(SysUser::getCreateUserId, getUserId()); } final String keyword = mpPageConvert.getKeyword(params); if (StrUtil.isNotEmpty(keyword)) { queryWrapper .lambda() .and(func -> func.like(SysUser::getUsername, keyword) .or() .like(SysUser::getMobile, keyword)); } IPage<SysUser> listPage = sysUserService.page(mpPageConvert.<SysUser>pageParamConvert(params), queryWrapper); return R.ok().setData(listPage); } /** * 获取登录的用户信息和菜单信息 */ @GetMapping(value = "/sysInfo") public R sysInfo() {<FILL_FUNCTION_BODY>} /** * 修改登录用户密码 */ @SysLog("修改密码") @RequestMapping(value = "/password", method = RequestMethod.POST) public R password(String password, String newPassword) { if (StrUtil.isEmpty(newPassword)) { return R.error("新密码不为能空"); } password = passwordEncoder.encode(password); newPassword = passwordEncoder.encode(newPassword); SysUser user = sysUserService.getById(getUserId()); if (!passwordEncoder.matches(password, user.getPassword())) { return R.error("原密码不正确"); } //更新密码 sysUserService.updatePassword(getUserId(), password, newPassword); return R.ok(); } /** * 保存用户 */ @SysLog("保存用户") @PostMapping(value = "/save") public R save(@RequestBody @Validated SysUser user) { user.setCreateUserId(getUserId()); sysUserService.saveUserRole(user); return R.ok(); } /** * 修改用户 */ @SysLog("修改用户") @PostMapping(value = "/update") public R update(@RequestBody @Validated SysUser user) { sysUserService.updateUserRole(user); return R.ok(); } /** * 删除用户 */ @SysLog("删除用户") @PostMapping(value = "/delete") public R delete(@RequestBody SysUser user) { if (user == null || user.getUserId() == null) { return R.error("参数错误"); } if (user.getUserId().equals(Constant.SUPER_ADMIN)) { return R.error("系统管理员不能删除"); } if (user.getUserId().equals(getUserId())) { return R.error("当前用户不能删除"); } sysUserService.removeById(user.getUserId()); return R.ok(); } }
// 用户菜单 final List<SysMenuNewVO> userMenu = sysMenuNewService.getUserMenu(); RouterInfo routerInfo = new RouterInfo(); routerInfo.setMenus(userMenu); // 用户信息 final SysUser sysUser = sysUserService.getById(getUserId()); UserInfoVO userInfo = new UserInfoVO(); userInfo.setUserId(sysUser.getUserId()); userInfo.setUserName(sysUser.getUsername()); userInfo.setName(sysUser.getName()); userInfo.setLoginIp(IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest())); final String photo = sysUser.getPhoto(); userInfo.setPhoto(photo == null ? "https://img0.baidu.com/it/u=1833472230,3849481738&fm=253&fmt=auto?w=200&h=200" : photo); userInfo.setRoles(new String[]{sysUser.getUserId().equals(Constant.SUPER_ADMIN) ? "admin" : "common"}); userInfo.setTime(DateUtil.now()); userInfo.setAuthBtnList(new String[]{"btn.add", "btn.del", "btn.edit", "btn.link"}); routerInfo.setUserInfo(userInfo); return R.ok().setData(routerInfo);
926
372
1,298
<methods>public non-sealed void <init>() <variables>protected com.suke.czx.common.utils.MPPageConvert mpPageConvert,public com.fasterxml.jackson.databind.ObjectMapper objectMapper
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/sys/service/impl/SysMenuNewServiceImpl.java
SysMenuNewServiceImpl
getRouterChildList
class SysMenuNewServiceImpl extends ServiceImpl<SysMenuNewMapper, SysMenuNew> implements SysMenuNewService { private final SysMenuNewMapper sysMenuNewMapper; private final SysRoleMapper sysRoleMapper; @Override public List<SysMenuNewVO> getUserMenu() { return getRouterChildList(0l); } public List<SysMenuNewVO> getRouterChildList(Long menuId) {<FILL_FUNCTION_BODY>} }
List<SysMenuNewVO> routerEntities = new ArrayList<>(); QueryWrapper<SysMenuNew> queryWrapper = new QueryWrapper<>(); final String userId = UserUtil.getUserId(); if (!userId.equals(Constant.SUPER_ADMIN)) { // 用户配置的菜单 final List<Long> menuIds = sysRoleMapper.queryAllMenuId(userId); if (CollUtil.isNotEmpty(menuIds)) { queryWrapper.lambda().in(SysMenuNew::getMenuId, menuIds); } else { return routerEntities; } } if (menuId != null) { queryWrapper.lambda().eq(SysMenuNew::getParentId, menuId); } queryWrapper.lambda().eq(SysMenuNew::isDisabled, true); List<SysMenuNew> sysMenus = sysMenuNewMapper.selectList(queryWrapper); if (CollUtil.isNotEmpty(sysMenus)) { sysMenus.forEach(sysMenu -> { SysMenuNewVO entity = new SysMenuNewVO(); entity.setMenuId(sysMenu.getMenuId()); entity.setParentId(sysMenu.getParentId()); entity.setPath(sysMenu.getPath()); entity.setName(sysMenu.getName()); entity.setComponent(sysMenu.getComponent()); entity.setRedirect(sysMenu.getRedirect()); entity.setTitle(sysMenu.getTitle()); entity.setOrderSort(sysMenu.getOrderSort()); // 设置mate RouterMetaVO metaVO = new RouterMetaVO(); metaVO.setTitle(sysMenu.getTitle()); metaVO.setIsLink(sysMenu.getIsLink()); metaVO.setHide(sysMenu.isHide()); metaVO.setKeepAlive(sysMenu.isKeepAlive()); metaVO.setAffix(sysMenu.isAffix()); metaVO.setIframe(sysMenu.isIframe()); metaVO.setIcon(sysMenu.getIcon()); metaVO.setRoles(sysMenu.getRoles()); entity.setMeta(metaVO); // 查询子菜单 entity.setChildren(this.getRouterChildList(sysMenu.getMenuId())); routerEntities.add(entity); }); } return routerEntities;
131
606
737
<methods>public void <init>() ,public com.suke.czx.modules.sys.mapper.SysMenuNewMapper getBaseMapper() ,public Class<com.suke.czx.modules.sys.entity.SysMenuNew> getEntityClass() ,public Map<java.lang.String,java.lang.Object> getMap(Wrapper<com.suke.czx.modules.sys.entity.SysMenuNew>) ,public V getObj(Wrapper<com.suke.czx.modules.sys.entity.SysMenuNew>, Function<? super java.lang.Object,V>) ,public com.suke.czx.modules.sys.entity.SysMenuNew getOne(Wrapper<com.suke.czx.modules.sys.entity.SysMenuNew>, boolean) ,public Optional<com.suke.czx.modules.sys.entity.SysMenuNew> getOneOpt(Wrapper<com.suke.czx.modules.sys.entity.SysMenuNew>, boolean) ,public boolean removeBatchByIds(Collection<?>, int) ,public boolean removeBatchByIds(Collection<?>, int, boolean) ,public boolean removeById(java.io.Serializable) ,public boolean removeById(java.io.Serializable, boolean) ,public boolean removeByIds(Collection<?>) ,public boolean saveBatch(Collection<com.suke.czx.modules.sys.entity.SysMenuNew>, int) ,public boolean saveOrUpdate(com.suke.czx.modules.sys.entity.SysMenuNew) ,public boolean saveOrUpdateBatch(Collection<com.suke.czx.modules.sys.entity.SysMenuNew>, int) ,public boolean updateBatchById(Collection<com.suke.czx.modules.sys.entity.SysMenuNew>, int) <variables>protected com.suke.czx.modules.sys.mapper.SysMenuNewMapper baseMapper,protected Class<com.suke.czx.modules.sys.entity.SysMenuNew> entityClass,protected org.apache.ibatis.logging.Log log,protected Class<com.suke.czx.modules.sys.mapper.SysMenuNewMapper> mapperClass,protected org.apache.ibatis.session.SqlSessionFactory sqlSessionFactory,protected final Class<?>[] typeArguments
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/sys/service/impl/SysRoleServiceImpl.java
SysRoleServiceImpl
updateRoleMenu
class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService { private final SysRoleMapper sysRoleMapper; private final SysRoleMenuService sysRoleMenuService; @Override @Transactional public void saveRoleMenu(SysRole role) { role.setCreateTime(new Date()); sysRoleMapper.insert(role); if (CollUtil.isNotEmpty(role.getMenuIdList())) { List<SysRoleMenu> sysRoleMenus = role.getMenuIdList().stream().map(id -> { SysRoleMenu menu = new SysRoleMenu(); menu.setMenuId(id); menu.setRoleId(role.getRoleId()); return menu; }).collect(Collectors.toList()); sysRoleMenuService.saveBatch(sysRoleMenus); } } @Override @Transactional public void updateRoleMenu(SysRole role) {<FILL_FUNCTION_BODY>} @Override public List<Long> queryRoleIdList(Long createUserId) { return sysRoleMapper.queryRoleIdList(createUserId); } @Override public void deleteBath(Long id) { baseMapper.deleteById(id); sysRoleMenuService.remove(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getRoleId, id)); } }
sysRoleMapper.updateById(role); if (CollUtil.isNotEmpty(role.getMenuIdList())) { sysRoleMenuService.remove(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getRoleId, role.getRoleId())); List<SysRoleMenu> sysRoleMenus = role.getMenuIdList().stream().map(id -> { SysRoleMenu menu = new SysRoleMenu(); menu.setMenuId(id); menu.setRoleId(role.getRoleId()); return menu; }).collect(Collectors.toList()); sysRoleMenuService.saveBatch(sysRoleMenus); }
370
175
545
<methods>public void <init>() ,public com.suke.czx.modules.sys.mapper.SysRoleMapper getBaseMapper() ,public Class<com.suke.czx.modules.sys.entity.SysRole> getEntityClass() ,public Map<java.lang.String,java.lang.Object> getMap(Wrapper<com.suke.czx.modules.sys.entity.SysRole>) ,public V getObj(Wrapper<com.suke.czx.modules.sys.entity.SysRole>, Function<? super java.lang.Object,V>) ,public com.suke.czx.modules.sys.entity.SysRole getOne(Wrapper<com.suke.czx.modules.sys.entity.SysRole>, boolean) ,public Optional<com.suke.czx.modules.sys.entity.SysRole> getOneOpt(Wrapper<com.suke.czx.modules.sys.entity.SysRole>, boolean) ,public boolean removeBatchByIds(Collection<?>, int) ,public boolean removeBatchByIds(Collection<?>, int, boolean) ,public boolean removeById(java.io.Serializable) ,public boolean removeById(java.io.Serializable, boolean) ,public boolean removeByIds(Collection<?>) ,public boolean saveBatch(Collection<com.suke.czx.modules.sys.entity.SysRole>, int) ,public boolean saveOrUpdate(com.suke.czx.modules.sys.entity.SysRole) ,public boolean saveOrUpdateBatch(Collection<com.suke.czx.modules.sys.entity.SysRole>, int) ,public boolean updateBatchById(Collection<com.suke.czx.modules.sys.entity.SysRole>, int) <variables>protected com.suke.czx.modules.sys.mapper.SysRoleMapper baseMapper,protected Class<com.suke.czx.modules.sys.entity.SysRole> entityClass,protected org.apache.ibatis.logging.Log log,protected Class<com.suke.czx.modules.sys.mapper.SysRoleMapper> mapperClass,protected org.apache.ibatis.session.SqlSessionFactory sqlSessionFactory,protected final Class<?>[] typeArguments
yzcheng90_X-SpringBoot
X-SpringBoot/src/main/java/com/suke/czx/modules/sys/service/impl/SysUserServiceImpl.java
SysUserServiceImpl
updatePassword
class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService { private final SysUserMapper sysUserMapper; private final SysUserRoleMapper sysUserRoleMapper; private final PasswordEncoder passwordEncoder; @Override @Transactional public void saveUserRole(SysUser user) { user.setCreateTime(new Date()); user.setPassword(passwordEncoder.encode(user.getPassword())); sysUserMapper.insert(user); sysUserRoleMapper.delete(Wrappers.<SysUserRole>update().lambda().eq(SysUserRole::getUserId, user.getUserId())); //保存用户与角色关系 saveUserRoleList(user); } @Override @Transactional public void updateUserRole(SysUser user) { if (StringUtils.isBlank(user.getPassword())) { user.setPassword(null); } else { user.setPassword(passwordEncoder.encode(user.getPassword())); } baseMapper.updateById(user); sysUserRoleMapper.delete(Wrappers.<SysUserRole>update().lambda().eq(SysUserRole::getUserId, user.getUserId())); //保存用户与角色关系 saveUserRoleList(user); } @Override public int updatePassword(String userId, String password, String newPassword) {<FILL_FUNCTION_BODY>} public void saveUserRoleList(SysUser user) { if (CollUtil.isNotEmpty(user.getRoleIdList())) { user.getRoleIdList().forEach(roleId -> { SysUserRole userRole = new SysUserRole(); userRole.setUserId(user.getUserId()); userRole.setRoleId(roleId); sysUserRoleMapper.insert(userRole); }); } } }
SysUser sysUser = new SysUser(); sysUser.setUserId(userId); sysUser.setPassword(newPassword); return sysUserMapper.updateById(sysUser);
489
52
541
<methods>public void <init>() ,public com.suke.czx.modules.sys.mapper.SysUserMapper getBaseMapper() ,public Class<com.suke.czx.modules.sys.entity.SysUser> getEntityClass() ,public Map<java.lang.String,java.lang.Object> getMap(Wrapper<com.suke.czx.modules.sys.entity.SysUser>) ,public V getObj(Wrapper<com.suke.czx.modules.sys.entity.SysUser>, Function<? super java.lang.Object,V>) ,public com.suke.czx.modules.sys.entity.SysUser getOne(Wrapper<com.suke.czx.modules.sys.entity.SysUser>, boolean) ,public Optional<com.suke.czx.modules.sys.entity.SysUser> getOneOpt(Wrapper<com.suke.czx.modules.sys.entity.SysUser>, boolean) ,public boolean removeBatchByIds(Collection<?>, int) ,public boolean removeBatchByIds(Collection<?>, int, boolean) ,public boolean removeById(java.io.Serializable) ,public boolean removeById(java.io.Serializable, boolean) ,public boolean removeByIds(Collection<?>) ,public boolean saveBatch(Collection<com.suke.czx.modules.sys.entity.SysUser>, int) ,public boolean saveOrUpdate(com.suke.czx.modules.sys.entity.SysUser) ,public boolean saveOrUpdateBatch(Collection<com.suke.czx.modules.sys.entity.SysUser>, int) ,public boolean updateBatchById(Collection<com.suke.czx.modules.sys.entity.SysUser>, int) <variables>protected com.suke.czx.modules.sys.mapper.SysUserMapper baseMapper,protected Class<com.suke.czx.modules.sys.entity.SysUser> entityClass,protected org.apache.ibatis.logging.Log log,protected Class<com.suke.czx.modules.sys.mapper.SysUserMapper> mapperClass,protected org.apache.ibatis.session.SqlSessionFactory sqlSessionFactory,protected final Class<?>[] typeArguments
knowm_XChange
XChange/xchange-ascendex/src/main/java/org/knowm/xchange/ascendex/AscendexExchange.java
AscendexExchange
remoteInit
class AscendexExchange extends BaseExchange implements Exchange { @Override protected void initServices() { this.marketDataService = new AscendexMarketDataService(this); this.accountService = new AscendexAccountService(this); this.tradeService = new AscendexTradeService(this); } @Override public ExchangeSpecification getDefaultExchangeSpecification() { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass()); exchangeSpecification.setSslUri("https://ascendex.com/"); exchangeSpecification.setExchangeName("Ascendex"); exchangeSpecification.setExchangeDescription( "Ascendex is a Bitcoin exchange with spot and future markets."); return exchangeSpecification; } @Override public void remoteInit() throws IOException, ExchangeException {<FILL_FUNCTION_BODY>} }
AscendexMarketDataServiceRaw raw = ((AscendexMarketDataServiceRaw) getMarketDataService()); exchangeMetaData = AscendexAdapters.adaptExchangeMetaData(raw.getAllAssets(), raw.getAllProducts());
231
70
301
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.service.account.AccountService getAccountService() ,public List<org.knowm.xchange.instrument.Instrument> getExchangeInstruments() ,public org.knowm.xchange.dto.meta.ExchangeMetaData getExchangeMetaData() ,public org.knowm.xchange.ExchangeSpecification getExchangeSpecification() ,public org.knowm.xchange.service.marketdata.MarketDataService getMarketDataService() ,public java.lang.String getMetaDataFileName(org.knowm.xchange.ExchangeSpecification) ,public SynchronizedValueFactory<java.lang.Long> getNonceFactory() ,public org.knowm.xchange.service.trade.TradeService getTradeService() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException,public java.lang.String toString() <variables>protected org.knowm.xchange.service.account.AccountService accountService,protected org.knowm.xchange.dto.meta.ExchangeMetaData exchangeMetaData,protected org.knowm.xchange.ExchangeSpecification exchangeSpecification,protected final Logger logger,protected org.knowm.xchange.service.marketdata.MarketDataService marketDataService,private final SynchronizedValueFactory<java.lang.Long> nonceFactory,protected org.knowm.xchange.service.trade.TradeService tradeService
knowm_XChange
XChange/xchange-ascendex/src/main/java/org/knowm/xchange/ascendex/dto/AscendexResponse.java
AscendexResponse
toString
class AscendexResponse<V> { @JsonIgnore private final String ac; @JsonIgnore private final String accountId; @JsonIgnore private final String message; private final Integer code; private final V data; public AscendexResponse( @JsonProperty("ac") String ac, @JsonProperty("accountId") String accountId, @JsonProperty("message") String message, @JsonProperty("code") Integer code, @JsonProperty("data") V data) { this.ac = ac; this.accountId = accountId; this.message = message; this.code = code; this.data = data; } public String getAc() { return ac; } public String getAccountId() { return accountId; } public String getMessage() { return message; } public Integer getCode() { return code; } public V getData() { return data; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "AscendexResponse{" + "ac='" + ac + '\'' + ", accountId='" + accountId + '\'' + ", message='" + message + '\'' + ", code=" + code + ", data=" + data + '}';
288
91
379
<no_super_class>
knowm_XChange
XChange/xchange-ascendex/src/main/java/org/knowm/xchange/ascendex/dto/marketdata/AscendexBarHistDto.java
AscendexBarHistDto
toString
class AscendexBarHistDto implements Serializable { private final String m; private final String symbol; private final AscendexBarDto bar; public AscendexBarHistDto( @JsonProperty("m") String m, @JsonProperty("s") String symbol, @JsonProperty("data") AscendexBarDto bar) { this.m = m; this.symbol = symbol; this.bar = bar; } public String getM() { return m; } public String getSymbol() { return symbol; } public AscendexBarDto getBar() { return bar; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "AscendexBarHistDto{" + "m='" + m + '\'' + ", symbol='" + symbol + '\'' + ", bar=" + bar + '}';
206
65
271
<no_super_class>
knowm_XChange
XChange/xchange-ascendex/src/main/java/org/knowm/xchange/ascendex/dto/marketdata/AscendexMarketTradesDto.java
AscendexMarketTradesData
toString
class AscendexMarketTradesData { private final String seqnum; private final BigDecimal price; private final BigDecimal quantity; private final Date timestamp; private final boolean isBuyerMaker; @JsonCreator public AscendexMarketTradesData( @JsonProperty("seqnum") String seqnum, @JsonProperty("p") BigDecimal price, @JsonProperty("q") BigDecimal quantity, @JsonProperty("ts") Date timestamp, @JsonProperty("bm") boolean isBuyerMaker) { this.seqnum = seqnum; this.price = price; this.quantity = quantity; this.timestamp = timestamp; this.isBuyerMaker = isBuyerMaker; } public String getSeqnum() { return seqnum; } public BigDecimal getPrice() { return price; } public BigDecimal getQuantity() { return quantity; } public Date getTimestamp() { return timestamp; } public boolean isBuyerMaker() { return isBuyerMaker; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "AscendexMarketTradesData{" + "seqnum='" + seqnum + '\'' + ", price=" + price + ", quantity=" + quantity + ", timestamp=" + timestamp + ", isBuyerMaker=" + isBuyerMaker + '}';
332
94
426
<no_super_class>
knowm_XChange
XChange/xchange-ascendex/src/main/java/org/knowm/xchange/ascendex/dto/trade/AscendexCancelOrderRequestPayload.java
AscendexCancelOrderRequestPayload
toString
class AscendexCancelOrderRequestPayload { @JsonProperty("orderId") private final String orderId; @JsonProperty("symbol") private final String symbol; @JsonProperty("time") private final Long time; public AscendexCancelOrderRequestPayload( @JsonProperty("orderId") String orderId, @JsonProperty("symbol") String symbol, @JsonProperty("time") Long time) { this.orderId = orderId; this.symbol = symbol; this.time = time; } public String getOrderId() { return orderId; } public String getSymbol() { return symbol; } public Long getTime() { return time; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "AscendexCancelOrderRequestPayload{" + ", orderId='" + orderId + '\'' + ", symbol='" + symbol + '\'' + ", time=" + time + '}';
221
68
289
<no_super_class>
knowm_XChange
XChange/xchange-ascendex/src/main/java/org/knowm/xchange/ascendex/dto/trade/AscendexOrderResponse.java
AscendexOrderResponse
toString
class AscendexOrderResponse { private final String ac; private final String accountId; private final String action; private final AscendexPlaceOrderInfo info; private final String status; private final String message; private final String reason; private final String code; public AscendexOrderResponse( @JsonProperty("ac") String ac, @JsonProperty("accountId") String accountId, @JsonProperty("action") String action, @JsonProperty("info") AscendexPlaceOrderInfo info, @JsonProperty("status") String status, @JsonProperty("message") String message, @JsonProperty("reason") String reason, @JsonProperty("code") String code) { this.ac = ac; this.accountId = accountId; this.action = action; this.info = info; this.status = status; this.message = message; this.reason = reason; this.code = code; } public String getAc() { return ac; } public String getAccountId() { return accountId; } public String getAction() { return action; } public AscendexPlaceOrderInfo getInfo() { return info; } public String getStatus() { return status; } public String getMessage() { return message; } public String getReason() { return reason; } public String getCode() { return code; } @Override public String toString() {<FILL_FUNCTION_BODY>} public static class AscendexPlaceOrderInfo { private final String id; private final String orderId; private final String orderType; private final String symbol; private final Date timestamp; public AscendexPlaceOrderInfo( @JsonProperty("id") String id, @JsonProperty("orderId") String orderId, @JsonProperty("orderType") String orderType, @JsonProperty("symbol") String symbol, @JsonProperty("timestamp") @JsonAlias({"lastExecTime"}) Long timestamp) { this.id = id; this.orderId = orderId; this.orderType = orderType; this.symbol = symbol; this.timestamp = timestamp == null ? null : new Date(timestamp); } public String getId() { return id; } public String getOrderId() { return orderId; } public String getOrderType() { return orderType; } public String getSymbol() { return symbol; } public Date getTimestamp() { return timestamp; } @Override public String toString() { return "{" + "id='" + id + '\'' + ", orderId='" + orderId + '\'' + ", orderType='" + orderType + '\'' + ", symbol='" + symbol + '\'' + ", timestamp=" + timestamp + '}'; } } }
return "AscendexPlaceOrderResponse{" + "ac='" + ac + '\'' + ", accountId='" + accountId + '\'' + ", action='" + action + '\'' + ", info=" + info + ", status='" + status + '\'' + ", message='" + message + '\'' + ", reason='" + reason + '\'' + ", code='" + code + '\'' + '}';
820
146
966
<no_super_class>
knowm_XChange
XChange/xchange-ascendex/src/main/java/org/knowm/xchange/ascendex/service/AscendexDigest.java
AscendexDigest
digestParams
class AscendexDigest extends BaseParamsDigest { public AscendexDigest(String secretKeyBase64) throws IllegalArgumentException { super(secretKeyBase64, HMAC_SHA_256); } public static AscendexDigest createInstance(String secretKeyBase64) { if (secretKeyBase64 != null) { return new AscendexDigest(secretKeyBase64); } else return null; } @Override public String digestParams(RestInvocation restInvocation) {<FILL_FUNCTION_BODY>} }
String message; if (restInvocation.getPath().contains("cash")) { message = restInvocation.getHttpHeadersFromParams().get("x-auth-timestamp") + restInvocation .getPath() .substring(restInvocation.getPath().lastIndexOf("cash") + 5); } else if (restInvocation.getPath().contains("margin")) { message = restInvocation.getHttpHeadersFromParams().get("x-auth-timestamp") + restInvocation .getPath() .substring(restInvocation.getPath().lastIndexOf("margin") + 7); } else { message = restInvocation.getHttpHeadersFromParams().get("x-auth-timestamp") + restInvocation.getPath().substring(restInvocation.getPath().lastIndexOf("/") + 1); } Mac mac256 = getMac(); mac256.update(message.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(mac256.doFinal()).trim();
156
281
437
<methods>public javax.crypto.Mac getMac() <variables>public static final java.lang.String HMAC_MD5,public static final java.lang.String HMAC_SHA_1,public static final java.lang.String HMAC_SHA_256,public static final java.lang.String HMAC_SHA_384,public static final java.lang.String HMAC_SHA_512,private final non-sealed javax.crypto.Mac mac
knowm_XChange
XChange/xchange-bankera/src/main/java/org/knowm/xchange/bankera/BankeraExchange.java
BankeraExchange
getDefaultExchangeSpecification
class BankeraExchange extends BaseExchange implements Exchange { private SynchronizedValueFactory<Long> nonceFactory = new TimestampIncrementingNonceFactory(); protected BankeraToken token; @Override protected void initServices() { this.accountService = new BankeraAccountService(this); this.marketDataService = new BankeraMarketDataService(this); this.tradeService = new BankeraTradeService(this); } @Override public ExchangeSpecification getDefaultExchangeSpecification() {<FILL_FUNCTION_BODY>} @Override public SynchronizedValueFactory<Long> getNonceFactory() { return nonceFactory; } public BankeraToken getToken() { if (token == null || token.getExpirationTime() < System.currentTimeMillis() + 30000L) { try { token = ((BankeraBaseService) accountService).createToken(); } catch (BankeraException e) { throw BankeraAdapters.adaptError(e); } } return token; } }
ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass()); exchangeSpecification.setSslUri("https://api-exchange.bankera.com"); exchangeSpecification.setHost("api-exchange.bankera.com"); exchangeSpecification.setPort(443); exchangeSpecification.setExchangeName("Bankera"); exchangeSpecification.setExchangeDescription("The Bankera exchange."); return exchangeSpecification;
283
117
400
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.service.account.AccountService getAccountService() ,public List<org.knowm.xchange.instrument.Instrument> getExchangeInstruments() ,public org.knowm.xchange.dto.meta.ExchangeMetaData getExchangeMetaData() ,public org.knowm.xchange.ExchangeSpecification getExchangeSpecification() ,public org.knowm.xchange.service.marketdata.MarketDataService getMarketDataService() ,public java.lang.String getMetaDataFileName(org.knowm.xchange.ExchangeSpecification) ,public SynchronizedValueFactory<java.lang.Long> getNonceFactory() ,public org.knowm.xchange.service.trade.TradeService getTradeService() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException,public java.lang.String toString() <variables>protected org.knowm.xchange.service.account.AccountService accountService,protected org.knowm.xchange.dto.meta.ExchangeMetaData exchangeMetaData,protected org.knowm.xchange.ExchangeSpecification exchangeSpecification,protected final Logger logger,protected org.knowm.xchange.service.marketdata.MarketDataService marketDataService,private final SynchronizedValueFactory<java.lang.Long> nonceFactory,protected org.knowm.xchange.service.trade.TradeService tradeService
knowm_XChange
XChange/xchange-bankera/src/main/java/org/knowm/xchange/bankera/dto/CreateOrderRequest.java
CreateOrderRequest
getEnum
class CreateOrderRequest { private static final String LIMIT_ORDER_TYPE = "limit"; private static final String MARKET_ORDER_TYPE = "market"; @JsonProperty("market") private final String market; @JsonProperty("side") private final String side; @JsonProperty("type") private final String type; @JsonProperty("price") private final String price; @JsonProperty("amount") private final String amount; @JsonProperty("client_order_id") private final String clientOrderId; @JsonProperty("nonce") private final Long nonce; public CreateOrderRequest( String market, String side, BigDecimal amount, String clientOrderId, Long nonce) { this.market = market; this.side = side; this.amount = amount.toPlainString(); this.type = MARKET_ORDER_TYPE; this.price = StringUtils.EMPTY; this.clientOrderId = clientOrderId; this.nonce = nonce; } public CreateOrderRequest( String market, String side, BigDecimal amount, BigDecimal price, String clientOrderId, Long nonce) { this.market = market; this.side = side; this.amount = amount.toPlainString(); this.type = LIMIT_ORDER_TYPE; this.price = price.toPlainString(); this.clientOrderId = clientOrderId; this.nonce = nonce; } public enum Side { BUY("buy"), SELL("sell"); private String side; Side(String side) { this.side = side; } public String getSide() { return this.side; } public static Side getEnum(String side) {<FILL_FUNCTION_BODY>} } }
for (Side currentEnum : Side.values()) { if (currentEnum.getSide().equalsIgnoreCase(side)) { return currentEnum; } } throw new UnsupportedOperationException("Unknown order side: " + side);
495
62
557
<no_super_class>
knowm_XChange
XChange/xchange-bibox/src/main/java/org/knowm/xchange/bibox/dto/BiboxCommands.java
BiboxCommands
json
class BiboxCommands extends ArrayList<BiboxCommand<?>> { public static final BiboxCommands ASSETS_CMD = BiboxCommands.of(new BiboxCommand<>("transfer/assets", new BiboxAllAssetsBody())); private static final ObjectMapper MAPPER = new ObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); private static final long serialVersionUID = 1L; private BiboxCommands() { super(); } public static BiboxCommands depositAddressCommand(String coinSymbol) { return BiboxCommands.of( new BiboxCommand<BiboxDepositAddressCommandBody>( "transfer/transferIn", new BiboxDepositAddressCommandBody(coinSymbol))); } public static BiboxCommands withdrawalsCommand(BiboxFundsCommandBody body) { return BiboxCommands.of( new BiboxCommand<BiboxFundsCommandBody>("transfer/transferOutList", body)); } public static BiboxCommands depositsCommand(BiboxFundsCommandBody body) { return BiboxCommands.of( new BiboxCommand<BiboxFundsCommandBody>("transfer/transferInList", body)); } public static BiboxCommands transferCommand(BiboxTransferCommandBody body) { return BiboxCommands.of( new BiboxCommand<BiboxTransferCommandBody>("transfer/transferOut", body)); } public static BiboxCommands of(List<BiboxCommand<?>> commands) { BiboxCommands cmds = new BiboxCommands(); cmds.addAll(commands); return cmds; } public static BiboxCommands of(BiboxCommand<?>... commands) { BiboxCommands cmds = new BiboxCommands(); cmds.addAll(Arrays.asList(commands)); return cmds; } public String json() {<FILL_FUNCTION_BODY>} }
try { return MAPPER.writeValueAsString(this); } catch (JsonProcessingException e) { throw new RuntimeException(e); }
558
45
603
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Collection<? extends BiboxCommand<?>>) ,public boolean add(BiboxCommand<?>) ,public void add(int, BiboxCommand<?>) ,public boolean addAll(Collection<? extends BiboxCommand<?>>) ,public boolean addAll(int, Collection<? extends BiboxCommand<?>>) ,public void clear() ,public java.lang.Object clone() ,public boolean contains(java.lang.Object) ,public void ensureCapacity(int) ,public boolean equals(java.lang.Object) ,public void forEach(Consumer<? super BiboxCommand<?>>) ,public BiboxCommand<?> get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public boolean isEmpty() ,public Iterator<BiboxCommand<?>> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<BiboxCommand<?>> listIterator() ,public ListIterator<BiboxCommand<?>> listIterator(int) ,public BiboxCommand<?> remove(int) ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean removeIf(Predicate<? super BiboxCommand<?>>) ,public void replaceAll(UnaryOperator<BiboxCommand<?>>) ,public boolean retainAll(Collection<?>) ,public BiboxCommand<?> set(int, BiboxCommand<?>) ,public int size() ,public void sort(Comparator<? super BiboxCommand<?>>) ,public Spliterator<BiboxCommand<?>> spliterator() ,public List<BiboxCommand<?>> subList(int, int) ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public void trimToSize() <variables>private static final java.lang.Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA,private static final int DEFAULT_CAPACITY,private static final java.lang.Object[] EMPTY_ELEMENTDATA,transient java.lang.Object[] elementData,private static final long serialVersionUID,private int size
knowm_XChange
XChange/xchange-bibox/src/main/java/org/knowm/xchange/bibox/service/BiboxMarketDataServiceRaw.java
BiboxMarketDataServiceRaw
getBiboxOrderBook
class BiboxMarketDataServiceRaw extends BiboxBaseService { private static final String TICKER_CMD = "ticker"; private static final String DEPTH_CMD = "depth"; private static final String ALL_TICKERS_CMD = "marketAll"; private static final String DEALS_CMD = "deals"; protected BiboxMarketDataServiceRaw(Exchange exchange) { super(exchange); } public BiboxTicker getBiboxTicker(CurrencyPair currencyPair) throws IOException { try { BiboxResponse<BiboxTicker> response = bibox.mdata(TICKER_CMD, toBiboxPair(currencyPair)); throwErrors(response); return response.getResult(); } catch (BiboxException e) { throw new ExchangeException(e.getMessage()); } } public BiboxOrderBook getBiboxOrderBook(CurrencyPair currencyPair, Integer depth) throws IOException {<FILL_FUNCTION_BODY>} public List<BiboxDeals> getBiboxDeals(CurrencyPair currencyPair, Integer depth) throws IOException { try { BiboxResponse<List<BiboxDeals>> response = bibox.deals(DEALS_CMD, BiboxAdapters.toBiboxPair(currencyPair), depth); throwErrors(response); return response.getResult(); } catch (BiboxException e) { throw new ExchangeException(e.getMessage(), e); } } public List<BiboxMarket> getAllBiboxMarkets() throws IOException { try { BiboxResponse<List<BiboxMarket>> response = bibox.marketAll(ALL_TICKERS_CMD); throwErrors(response); return response.getResult(); } catch (BiboxException e) { throw new ExchangeException(e.getMessage()); } } public List<BiboxOrderBook> getBiboxOrderBooks( Integer depth, Collection<Instrument> currencyPairs) { try { List<BiboxCommand<?>> allCommands = currencyPairs.stream() .distinct() .filter(Objects::nonNull) .map(BiboxAdapters::toBiboxPair) .map(pair -> new BiboxOrderBookCommand(pair, depth)) .collect(Collectors.toList()); BiboxMultipleResponses<BiboxOrderBook> response = bibox.orderBooks(BiboxCommands.of(allCommands).json()); throwErrors(response); return response.getResult().stream() .map(BiboxResponse::getResult) .collect(Collectors.toList()); } catch (BiboxException e) { throw new ExchangeException(e.getMessage()); } } }
try { BiboxResponse<BiboxOrderBook> response = bibox.orderBook(DEPTH_CMD, BiboxAdapters.toBiboxPair(currencyPair), depth); throwErrors(response); return response.getResult(); } catch (BiboxException e) { throw new ExchangeException(e.getMessage()); }
748
97
845
<methods><variables>protected final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.bibox.BiboxAuthenticated bibox,protected final non-sealed ParamsDigest signatureCreator
knowm_XChange
XChange/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/account/AssetDetail.java
AssetDetail
toString
class AssetDetail { private final String minWithdrawAmount; private final boolean depositStatus; private final BigDecimal withdrawFee; private final boolean withdrawStatus; public AssetDetail( @JsonProperty("minWithdrawAmount") String minWithdrawAmount, @JsonProperty("depositStatus") boolean depositStatus, @JsonProperty("withdrawFee") BigDecimal withdrawFee, @JsonProperty("withdrawStatus") boolean withdrawStatus) { this.minWithdrawAmount = minWithdrawAmount; this.depositStatus = depositStatus; this.withdrawFee = withdrawFee; this.withdrawStatus = withdrawStatus; } public String getMinWithdrawAmount() { return minWithdrawAmount; } public boolean isDepositStatus() { return depositStatus; } public BigDecimal getWithdrawFee() { return withdrawFee; } public boolean isWithdrawStatus() { return withdrawStatus; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "AssetDetail{" + "minWithdrawAmount = '" + minWithdrawAmount + '\'' + ",depositStatus = '" + depositStatus + '\'' + ",withdrawFee = '" + withdrawFee + '\'' + ",withdrawStatus = '" + withdrawStatus + '\'' + "}";
285
99
384
<no_super_class>
knowm_XChange
XChange/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/account/BinanceBalance.java
BinanceBalance
toString
class BinanceBalance { private final Currency currency; private final BigDecimal free; private final BigDecimal locked; public BinanceBalance( @JsonProperty("asset") String asset, @JsonProperty("free") BigDecimal free, @JsonProperty("locked") BigDecimal locked) { this.currency = Currency.getInstance(asset); this.locked = locked; this.free = free; } public Currency getCurrency() { return currency; } public BigDecimal getTotal() { return free.add(locked); } public BigDecimal getAvailable() { return free; } public BigDecimal getLocked() { return locked; } public String toString() {<FILL_FUNCTION_BODY>} }
return "[" + currency + ", free=" + free + ", locked=" + locked + "]";
224
28
252
<no_super_class>
knowm_XChange
XChange/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinanceKline.java
BinanceKline
toString
class BinanceKline { private final Instrument instrument; private final KlineInterval interval; private final long openTime; private final BigDecimal open; private final BigDecimal high; private final BigDecimal low; private final BigDecimal close; private final BigDecimal volume; private final long closeTime; private final BigDecimal quoteAssetVolume; private final long numberOfTrades; private final BigDecimal takerBuyBaseAssetVolume; private final BigDecimal takerBuyQuoteAssetVolume; private final boolean closed; public BinanceKline(Instrument instrument, KlineInterval interval, Object[] obj) { this.instrument = instrument; this.interval = interval; this.openTime = Long.parseLong(obj[0].toString()); this.open = new BigDecimal(obj[1].toString()); this.high = new BigDecimal(obj[2].toString()); this.low = new BigDecimal(obj[3].toString()); this.close = new BigDecimal(obj[4].toString()); this.volume = new BigDecimal(obj[5].toString()); this.closeTime = Long.parseLong(obj[6].toString()); this.quoteAssetVolume = new BigDecimal(obj[7].toString()); this.numberOfTrades = Long.parseLong(obj[8].toString()); this.takerBuyBaseAssetVolume = new BigDecimal(obj[9].toString()); this.takerBuyQuoteAssetVolume = new BigDecimal(obj[10].toString()); this.closed = Boolean.parseBoolean(obj[11].toString()); } public BigDecimal getAveragePrice() { return low.add(high).divide(new BigDecimal("2"), MathContext.DECIMAL32); } public String toString() {<FILL_FUNCTION_BODY>} }
String tstamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(openTime); return String.format( "[%s] %s %s O:%.6f A:%.6f C:%.6f", instrument, tstamp, interval, open, getAveragePrice(), close);
486
85
571
<no_super_class>
knowm_XChange
XChange/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/meta/exchangeinfo/Filter.java
Filter
toString
class Filter { private String maxPrice; private String filterType; private String tickSize; private String minPrice; private String minQty; private String maxQty; private String stepSize; private String minNotional; public String getMaxPrice() { return maxPrice; } public void setMaxPrice(String maxPrice) { this.maxPrice = maxPrice; } public String getFilterType() { return filterType; } public void setFilterType(String filterType) { this.filterType = filterType; } public String getTickSize() { return tickSize; } public void setTickSize(String tickSize) { this.tickSize = tickSize; } public String getMinPrice() { return minPrice; } public void setMinPrice(String minPrice) { this.minPrice = minPrice; } public String getMinQty() { return minQty; } public void setMinQty(String minQty) { this.minQty = minQty; } public String getMaxQty() { return maxQty; } public void setMaxQty(String maxQty) { this.maxQty = maxQty; } public String getStepSize() { return stepSize; } public void setStepSize(String stepSize) { this.stepSize = stepSize; } public String getMinNotional() { return minNotional; } public void setMinNotional(String minNotional) { this.minNotional = minNotional; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Filter{" + "maxPrice='" + maxPrice + '\'' + ", filterType='" + filterType + '\'' + ", tickSize='" + tickSize + '\'' + ", minPrice='" + minPrice + '\'' + ", minQty='" + minQty + '\'' + ", maxQty='" + maxQty + '\'' + ", stepSize='" + stepSize + '\'' + ", minNotional='" + minNotional + '\'' + '}';
486
165
651
<no_super_class>
knowm_XChange
XChange/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/meta/exchangeinfo/RateLimit.java
RateLimit
toString
class RateLimit { private String limit; private String interval; private String intervalNum; private String rateLimitType; public String getLimit() { return limit; } public void setLimit(String limit) { this.limit = limit; } public String getInterval() { return interval; } public void setInterval(String interval) { this.interval = interval; } public String getIntervalNum() { return intervalNum; } public void setIntervalNum(String intervalNum) { this.intervalNum = intervalNum; } public String getRateLimitType() { return rateLimitType; } public void setRateLimitType(String rateLimitType) { this.rateLimitType = rateLimitType; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "ClassPojo [limit = " + limit + ", interval = " + interval + ", intervalNum = " + intervalNum + ", rateLimitType = " + rateLimitType + "]";
240
63
303
<no_super_class>
knowm_XChange
XChange/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceAccountServiceRaw.java
BinanceAccountServiceRaw
withdrawHistory
class BinanceAccountServiceRaw extends BinanceBaseService { public BinanceAccountServiceRaw( BinanceExchange exchange, ResilienceRegistries resilienceRegistries) { super(exchange, resilienceRegistries); } public BinanceAccountInformation account() throws BinanceException, IOException { return decorateApiCall( () -> binance.account(getRecvWindow(), getTimestampFactory(), apiKey, signatureCreator)) .withRetry(retry("account")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER), 5) .call(); } public BinanceFutureAccountInformation futuresAccount() throws BinanceException, IOException { return decorateApiCall( () -> binanceFutures.futuresAccount( getRecvWindow(), getTimestampFactory(), apiKey, signatureCreator)) .withRetry(retry("futures-account")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER), 5) .call(); } public WithdrawResponse withdraw(String coin, String address, BigDecimal amount) throws IOException, BinanceException { // the name parameter seams to be mandatory String name = address.length() <= 10 ? address : address.substring(0, 10); return withdraw(coin, address, null, amount, name); } public WithdrawResponse withdraw( String coin, String address, String addressTag, BigDecimal amount) throws IOException, BinanceException { // the name parameter seams to be mandatory String name = address.length() <= 10 ? address : address.substring(0, 10); return withdraw(coin, address, addressTag, amount, name); } private WithdrawResponse withdraw( String coin, String address, String addressTag, BigDecimal amount, String name) throws IOException, BinanceException { return decorateApiCall( () -> binance.withdraw( coin, address, addressTag, amount, name, getRecvWindow(), getTimestampFactory(), apiKey, signatureCreator)) .withRetry(retry("withdraw", NON_IDEMPOTENT_CALLS_RETRY_CONFIG_NAME)) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER), 5) .call(); } public DepositAddress requestDepositAddress(Currency currency) throws IOException { return decorateApiCall( () -> binance.depositAddress( BinanceAdapters.toSymbol(currency), getRecvWindow(), getTimestampFactory(), apiKey, signatureCreator)) .withRetry(retry("depositAddress")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER)) .call(); } public Map<String, AssetDetail> requestAssetDetail() throws IOException { return decorateApiCall( () -> binance.assetDetail( getRecvWindow(), getTimestampFactory(), apiKey, signatureCreator)) .withRetry(retry("assetDetail")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER)) .call(); } public List<BinanceDeposit> depositHistory(String asset, Long startTime, Long endTime) throws BinanceException, IOException { return decorateApiCall( () -> binance.depositHistory( asset, startTime, endTime, getRecvWindow(), getTimestampFactory(), apiKey, signatureCreator)) .withRetry(retry("depositHistory")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER)) .call(); } public List<BinanceWithdraw> withdrawHistory(String asset, Long startTime, Long endTime) throws BinanceException, IOException {<FILL_FUNCTION_BODY>} public List<AssetDividendResponse.AssetDividend> getAssetDividend(Long startTime, Long endTime) throws BinanceException, IOException { return getAssetDividend("", startTime, endTime); } public List<AssetDividendResponse.AssetDividend> getAssetDividend( String asset, Long startTime, Long endTime) throws BinanceException, IOException { return decorateApiCall( () -> binance.assetDividend( asset, startTime, endTime, getRecvWindow(), getTimestampFactory(), super.apiKey, super.signatureCreator)) .withRetry(retry("assetDividend")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER)) .call() .getData(); } public List<TransferHistory> getTransferHistory( String fromEmail, Long startTime, Long endTime, Integer page, Integer limit) throws BinanceException, IOException { return decorateApiCall( () -> binance.transferHistory( fromEmail, startTime, endTime, page, limit, getRecvWindow(), getTimestampFactory(), super.apiKey, super.signatureCreator)) .withRetry(retry("transferHistory")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER)) .call(); } public List<TransferSubUserHistory> getSubUserHistory( String asset, Integer type, Long startTime, Long endTime, Integer limit) throws BinanceException, IOException { return decorateApiCall( () -> binance.transferSubUserHistory( asset, type, startTime, endTime, limit, getRecvWindow(), getTimestampFactory(), super.apiKey, super.signatureCreator)) .withRetry(retry("transferSubUserHistory")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER)) .call(); } }
return decorateApiCall( () -> binance.withdrawHistory( asset, startTime, endTime, getRecvWindow(), getTimestampFactory(), apiKey, signatureCreator)) .withRetry(retry("withdrawHistory")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER)) .call();
1,641
108
1,749
<methods>public org.knowm.xchange.binance.dto.meta.exchangeinfo.BinanceExchangeInfo getExchangeInfo() throws java.io.IOException,public org.knowm.xchange.binance.dto.meta.exchangeinfo.BinanceExchangeInfo getFutureExchangeInfo() throws java.io.IOException,public java.lang.Long getRecvWindow() ,public org.knowm.xchange.binance.dto.meta.BinanceSystemStatus getSystemStatus() throws java.io.IOException,public SynchronizedValueFactory<java.lang.Long> getTimestampFactory() <variables>protected final Logger LOG,protected final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.binance.BinanceAuthenticated binance,protected final non-sealed org.knowm.xchange.binance.BinanceFuturesAuthenticated binanceFutures,protected final non-sealed org.knowm.xchange.binance.BinanceFuturesAuthenticated inverseBinanceFutures,protected final non-sealed ParamsDigest signatureCreator
knowm_XChange
XChange/xchange-bitbay/src/main/java/org/knowm/xchange/bitbay/BitbayExchange.java
BitbayExchange
initServices
class BitbayExchange extends BaseExchange implements Exchange { private final SynchronizedValueFactory<Long> nonceFactory = new CurrentTimeIncrementalNonceFactory(TimeUnit.SECONDS); @Override public ExchangeSpecification getDefaultExchangeSpecification() { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass()); exchangeSpecification.setSslUri("https://bitbay.net/API/"); exchangeSpecification.setHost("bitbay.net"); exchangeSpecification.setPort(80); exchangeSpecification.setExchangeName("Bitbay"); exchangeSpecification.setExchangeDescription( "Bitbay is a Bitcoin exchange based in Katowice, Poland."); return exchangeSpecification; } @Override protected void initServices() {<FILL_FUNCTION_BODY>} @Override public SynchronizedValueFactory<Long> getNonceFactory() { return nonceFactory; } }
this.marketDataService = new BitbayMarketDataService(this); this.tradeService = new BitbayTradeService(this); this.accountService = new BitbayAccountService(this);
249
53
302
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.service.account.AccountService getAccountService() ,public List<org.knowm.xchange.instrument.Instrument> getExchangeInstruments() ,public org.knowm.xchange.dto.meta.ExchangeMetaData getExchangeMetaData() ,public org.knowm.xchange.ExchangeSpecification getExchangeSpecification() ,public org.knowm.xchange.service.marketdata.MarketDataService getMarketDataService() ,public java.lang.String getMetaDataFileName(org.knowm.xchange.ExchangeSpecification) ,public SynchronizedValueFactory<java.lang.Long> getNonceFactory() ,public org.knowm.xchange.service.trade.TradeService getTradeService() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException,public java.lang.String toString() <variables>protected org.knowm.xchange.service.account.AccountService accountService,protected org.knowm.xchange.dto.meta.ExchangeMetaData exchangeMetaData,protected org.knowm.xchange.ExchangeSpecification exchangeSpecification,protected final Logger logger,protected org.knowm.xchange.service.marketdata.MarketDataService marketDataService,private final SynchronizedValueFactory<java.lang.Long> nonceFactory,protected org.knowm.xchange.service.trade.TradeService tradeService
knowm_XChange
XChange/xchange-bitbay/src/main/java/org/knowm/xchange/bitbay/dto/marketdata/BitbayTrade.java
BitbayTrade
toString
class BitbayTrade { private final long date; private final BigDecimal price; private final BigDecimal amount; private final String tid; /** * Constructor * * @param date * @param price * @param amount * @param tid */ public BitbayTrade( @JsonProperty("date") long date, @JsonProperty("price") BigDecimal price, @JsonProperty("amount") BigDecimal amount, @JsonProperty("tid") String tid) { this.date = date; this.price = price; this.amount = amount; this.tid = tid; } public long getDate() { return date; } public BigDecimal getPrice() { return price; } public BigDecimal getAmount() { return amount; } public String getTid() { return tid; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BitbayTrade{" + "date=" + date + ", price=" + price + ", amount=" + amount + ", tid='" + tid + '\'' + '}';
283
70
353
<no_super_class>
knowm_XChange
XChange/xchange-bitbay/src/main/java/org/knowm/xchange/bitbay/service/BitbayAccountService.java
BitbayAccountService
withdrawFunds
class BitbayAccountService extends BitbayAccountServiceRaw implements AccountService { public BitbayAccountService(Exchange exchange) { super(exchange); } @Override public AccountInfo getAccountInfo() throws IOException { return BitbayAdapters.adaptAccountInfo( exchange.getExchangeSpecification().getUserName(), getBitbayAccountInfo()); } @Override public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException { return withdrawFunds(new DefaultWithdrawFundsParams(address, currency, amount)); } @Override public String withdrawFunds(WithdrawFundsParams params) throws IOException {<FILL_FUNCTION_BODY>} @Override public String requestDepositAddress(Currency currency, String... args) throws IOException { throw new NotAvailableFromExchangeException(); } @Override public TradeHistoryParams createFundingHistoryParams() { throw new NotAvailableFromExchangeException(); } @Override public List<FundingRecord> getFundingHistory(TradeHistoryParams params) throws IOException { Currency currency = null; if (params instanceof TradeHistoryParamCurrency) { TradeHistoryParamCurrency tradeHistoryParamCurrency = (TradeHistoryParamCurrency) params; currency = tradeHistoryParamCurrency.getCurrency(); } Integer limit = 1000; if (params instanceof TradeHistoryParamLimit) { limit = ((TradeHistoryParamLimit) params).getLimit(); } return history(currency, limit); } public static class BitbayFundingHistory implements TradeHistoryParamCurrency, TradeHistoryParamLimit { private Currency currency; private Integer limit; public BitbayFundingHistory(Currency currency, Integer limit) { this.currency = currency; this.limit = limit; } public BitbayFundingHistory() {} @Override public Currency getCurrency() { return currency; } @Override public void setCurrency(Currency currency) { this.currency = currency; } @Override public Integer getLimit() { return limit; } @Override public void setLimit(Integer limit) { this.limit = limit; } } }
if (params instanceof DefaultWithdrawFundsParams) { DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params; transfer(defaultParams.getCurrency(), defaultParams.getAmount(), defaultParams.getAddress()); return "Success"; } else if (params instanceof BitbayWithdrawFundsSwiftParams) { BitbayWithdrawFundsSwiftParams bicParams = (BitbayWithdrawFundsSwiftParams) params; withdraw( bicParams.getCurrency(), bicParams.getAmount(), bicParams.getAccount(), bicParams.isExpress(), bicParams.getBic()); return "Success"; } throw new NotAvailableFromExchangeException();
601
193
794
<methods>public void <init>(org.knowm.xchange.Exchange) ,public org.knowm.xchange.bitbay.dto.acount.BitbayAccountInfoResponse getBitbayAccountInfo() throws java.io.IOException,public List<org.knowm.xchange.dto.account.FundingRecord> history(org.knowm.xchange.currency.Currency, int) ,public org.knowm.xchange.bitbay.dto.BitbayBaseResponse transfer(org.knowm.xchange.currency.Currency, java.math.BigDecimal, java.lang.String) ,public org.knowm.xchange.bitbay.dto.BitbayBaseResponse withdraw(org.knowm.xchange.currency.Currency, java.math.BigDecimal, java.lang.String, boolean, java.lang.String) <variables>
knowm_XChange
XChange/xchange-bitbay/src/main/java/org/knowm/xchange/bitbay/service/BitbayMarketDataServiceRaw.java
BitbayMarketDataServiceRaw
getBitbayTrades
class BitbayMarketDataServiceRaw extends BitbayBaseService { /** * Constructor * * @param exchange */ protected BitbayMarketDataServiceRaw(Exchange exchange) { super(exchange); } public BitbayTicker getBitbayTicker(CurrencyPair currencyPair) throws IOException { return bitbay.getBitbayTicker( currencyPair.base.getCurrencyCode().toUpperCase() + currencyPair.counter.getCurrencyCode()); } public BitbayOrderBook getBitbayOrderBook(CurrencyPair currencyPair) throws IOException { return bitbay.getBitbayOrderBook( currencyPair.base.getCurrencyCode().toUpperCase() + currencyPair.counter.getCurrencyCode()); } public BitbayTrade[] getBitbayTrades(CurrencyPair currencyPair, Object[] args) throws IOException {<FILL_FUNCTION_BODY>} }
long since = 0; if (args.length >= 1 && args[0] != null) { since = ((Number) args[0]).longValue(); } String sort = "asc"; if (args.length >= 2) { sort = (String) args[1]; } int limit = 50; // param works up to 150 if (args.length == 3) { limit = ((Number) args[2]).intValue(); } return bitbay.getBitbayTrades( currencyPair.base.getCurrencyCode().toUpperCase() + currencyPair.counter.getCurrencyCode(), since, sort, limit);
241
178
419
<methods><variables>final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.bitbay.Bitbay bitbay,final non-sealed org.knowm.xchange.bitbay.BitbayAuthenticated bitbayAuthenticated,final non-sealed ParamsDigest sign
knowm_XChange
XChange/xchange-bitbay/src/main/java/org/knowm/xchange/bitbay/v3/BitbayDigest.java
BitbayDigest
digestParams
class BitbayDigest extends BaseParamsDigest { private BitbayDigest(String secretKeyBase64) throws IllegalArgumentException { super(secretKeyBase64, HMAC_SHA_512); } public static BitbayDigest createInstance(String secretKeyBase64) { return secretKeyBase64 == null ? null : new BitbayDigest(secretKeyBase64); } @Override public String digestParams(RestInvocation restInvocation) {<FILL_FUNCTION_BODY>} }
try { Map<String, String> headers = restInvocation.getHttpHeadersFromParams(); String apiKey = headers.get("API-Key"); Long requestTimestamp = Long.parseLong(headers.get("Request-Timestamp")); String hashContent = apiKey + requestTimestamp; Mac mac = getMac(); mac.update(hashContent.getBytes("UTF-8")); return String.format("%0128x", new BigInteger(1, mac.doFinal())); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Illegal encoding, check the code.", e); }
138
153
291
<methods>public javax.crypto.Mac getMac() <variables>public static final java.lang.String HMAC_MD5,public static final java.lang.String HMAC_SHA_1,public static final java.lang.String HMAC_SHA_256,public static final java.lang.String HMAC_SHA_384,public static final java.lang.String HMAC_SHA_512,private final non-sealed javax.crypto.Mac mac
knowm_XChange
XChange/xchange-bitbay/src/main/java/org/knowm/xchange/bitbay/v3/service/BitbayBaseService.java
BitbayBaseService
checkError
class BitbayBaseService extends BaseExchangeService implements BaseService { final BitbayAuthenticated bitbayAuthenticated; final ParamsDigest sign; final String apiKey; /** * Constructor * * @param exchange */ BitbayBaseService(Exchange exchange) { super(exchange); bitbayAuthenticated = ExchangeRestProxyBuilder.forInterface( BitbayAuthenticated.class, exchange.getExchangeSpecification()) .build(); sign = BitbayDigest.createInstance(exchange.getExchangeSpecification().getSecretKey()); apiKey = exchange.getExchangeSpecification().getApiKey(); } void checkError(BitbayBaseResponse response) {<FILL_FUNCTION_BODY>} }
if (response.getStatus().equalsIgnoreCase("fail")) { List<String> errors = response.getErrors(); if (errors == null || errors.isEmpty()) { throw new ExchangeException("Bitbay API unexpected error"); } Iterator<String> errorsIterator = errors.iterator(); StringBuilder message = new StringBuilder("Bitbay API error: ").append(errorsIterator.next()); while (errorsIterator.hasNext()) { message.append(", ").append(errorsIterator.next()); } throw new ExchangeException(message.toString()); }
201
143
344
<methods>public void verifyOrder(org.knowm.xchange.dto.trade.LimitOrder) ,public void verifyOrder(org.knowm.xchange.dto.trade.MarketOrder) <variables>protected final non-sealed org.knowm.xchange.Exchange exchange
knowm_XChange
XChange/xchange-bitbay/src/main/java/org/knowm/xchange/bitbay/v3/service/BitbayTradeServiceRaw.java
BitbayTradeServiceRaw
getBitbayTransactions
class BitbayTradeServiceRaw extends BitbayBaseService { BitbayTradeServiceRaw(Exchange exchange) { super(exchange); } public BitbayUserTrades getBitbayTransactions(BitbayUserTradesQuery query) throws IOException, ExchangeException {<FILL_FUNCTION_BODY>} }
final String jsonQuery = ObjectMapperHelper.toCompactJSON(query); final BitbayUserTrades response = bitbayAuthenticated.getTransactionHistory( apiKey, sign, exchange.getNonceFactory(), UUID.randomUUID(), jsonQuery); checkError(response); return response;
84
77
161
<methods><variables>final non-sealed java.lang.String apiKey,final non-sealed org.knowm.xchange.bitbay.v3.BitbayAuthenticated bitbayAuthenticated,final non-sealed ParamsDigest sign
knowm_XChange
XChange/xchange-bitcoinaverage/src/main/java/org/knowm/xchange/bitcoinaverage/BitcoinAverageAdapters.java
BitcoinAverageAdapters
adaptMetaData
class BitcoinAverageAdapters { /** private Constructor */ private BitcoinAverageAdapters() {} /** * Adapts a BitcoinAverageTicker to a Ticker Object * * @param bitcoinAverageTicker * @return Ticker */ public static Ticker adaptTicker( BitcoinAverageTicker bitcoinAverageTicker, CurrencyPair currencyPair) { BigDecimal last = bitcoinAverageTicker.getLast(); BigDecimal bid = bitcoinAverageTicker.getBid(); BigDecimal ask = bitcoinAverageTicker.getAsk(); Date timestamp = bitcoinAverageTicker.getTimestamp(); BigDecimal volume = bitcoinAverageTicker.getVolume(); return new Ticker.Builder() .currencyPair(currencyPair) .last(last) .bid(bid) .ask(ask) .volume(volume) .timestamp(timestamp) .build(); } public static ExchangeMetaData adaptMetaData( BitcoinAverageTickers tickers, ExchangeMetaData bAMetaData) {<FILL_FUNCTION_BODY>} }
Map<Instrument, InstrumentMetaData> currencyPairs = new HashMap<>(); for (String currency : tickers.getTickers().keySet()) { if (!currency.startsWith("BTC")) { throw new IllegalStateException("Unsupported currency: " + currency); } currencyPairs.put(new CurrencyPair(BTC, Currency.getInstance(currency.substring(3))), null); } return new ExchangeMetaData( currencyPairs, Collections.<Currency, CurrencyMetaData>emptyMap(), null, null, null);
298
146
444
<no_super_class>
knowm_XChange
XChange/xchange-bitcoinaverage/src/main/java/org/knowm/xchange/bitcoinaverage/service/BitcoinAverageMarketDataServiceRaw.java
BitcoinAverageMarketDataServiceRaw
getBitcoinAverageTicker
class BitcoinAverageMarketDataServiceRaw extends BitcoinAverageBaseService { private final BitcoinAverage bitcoinAverage; /** * Constructor * * @param exchange */ public BitcoinAverageMarketDataServiceRaw(Exchange exchange) { super(exchange); this.bitcoinAverage = ExchangeRestProxyBuilder.forInterface( BitcoinAverage.class, exchange.getExchangeSpecification()) .build(); } public BitcoinAverageTicker getBitcoinAverageTicker(String tradable, String currency) throws IOException {<FILL_FUNCTION_BODY>} public BitcoinAverageTickers getBitcoinAverageShortTickers(String crypto) throws IOException { // Request data BitcoinAverageTickers bitcoinAverageTicker = bitcoinAverage.getShortTickers(crypto); return bitcoinAverageTicker; } }
// Request data BitcoinAverageTicker bitcoinAverageTicker = bitcoinAverage.getTicker(tradable + currency); return bitcoinAverageTicker;
238
49
287
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>
knowm_XChange
XChange/xchange-bitcoincharts/src/main/java/org/knowm/xchange/bitcoincharts/BitcoinChartsAdapters.java
BitcoinChartsAdapters
adaptTicker
class BitcoinChartsAdapters { /** private Constructor */ private BitcoinChartsAdapters() {} /** * Adapts a BitcoinChartsTicker[] to a Ticker Object * * @param bitcoinChartsTickers * @return */ public static Ticker adaptTicker( BitcoinChartsTicker[] bitcoinChartsTickers, CurrencyPair currencyPair) {<FILL_FUNCTION_BODY>} public static ExchangeMetaData adaptMetaData( ExchangeMetaData exchangeMetaData, BitcoinChartsTicker[] tickers) { Map<Instrument, InstrumentMetaData> pairs = new HashMap<>(); for (BitcoinChartsTicker ticker : tickers) { BigDecimal anyPrice = firstNonNull( ticker.getAsk(), ticker.getBid(), ticker.getClose(), ticker.getHigh(), ticker.getHigh()); int scale = anyPrice != null ? anyPrice.scale() : 0; pairs.put( new CurrencyPair(Currency.BTC, Currency.getInstance(ticker.getSymbol())), new InstrumentMetaData.Builder().priceScale(scale).build()); } return new ExchangeMetaData( pairs, exchangeMetaData.getCurrencies(), exchangeMetaData.getPublicRateLimits(), exchangeMetaData.getPrivateRateLimits(), exchangeMetaData.isShareRateLimits()); } private static <T> T firstNonNull(T... objects) { for (T o : objects) { if (o != null) { return o; } } return null; } }
for (BitcoinChartsTicker bitcoinChartsTicker : bitcoinChartsTickers) { if (bitcoinChartsTicker.getSymbol().equals(currencyPair.counter.getCurrencyCode())) { BigDecimal last = bitcoinChartsTicker.getClose() != null ? bitcoinChartsTicker.getClose() : null; BigDecimal bid = bitcoinChartsTicker.getBid() != null ? bitcoinChartsTicker.getBid() : null; BigDecimal ask = bitcoinChartsTicker.getAsk() != null ? bitcoinChartsTicker.getAsk() : null; BigDecimal high = bitcoinChartsTicker.getHigh() != null ? bitcoinChartsTicker.getHigh() : null; BigDecimal low = bitcoinChartsTicker.getLow() != null ? bitcoinChartsTicker.getLow() : null; BigDecimal volume = bitcoinChartsTicker.getVolume(); Date timeStamp = new Date(bitcoinChartsTicker.getLatestTrade() * 1000L); return new Ticker.Builder() .currencyPair(currencyPair) .instrument(currencyPair) .last(last) .bid(bid) .ask(ask) .high(high) .low(low) .volume(volume) .timestamp(timeStamp) .build(); } } return null;
437
379
816
<no_super_class>
knowm_XChange
XChange/xchange-bitcoincharts/src/main/java/org/knowm/xchange/bitcoincharts/BitcoinChartsExchange.java
BitcoinChartsExchange
remoteInit
class BitcoinChartsExchange extends BaseExchange implements Exchange { /** Constructor */ public BitcoinChartsExchange() {} @Override protected void initServices() { this.marketDataService = new BitcoinChartsMarketDataService(this); } @Override public ExchangeSpecification getDefaultExchangeSpecification() { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass()); exchangeSpecification.setPlainTextUri("http://api.bitcoincharts.com"); exchangeSpecification.setHost("api.bitcoincharts.com"); exchangeSpecification.setPort(80); exchangeSpecification.setExchangeName("BitcoinCharts"); exchangeSpecification.setExchangeDescription( "Bitcoin charts provides financial and technical data related to the Bitcoin network."); return exchangeSpecification; } @Override public SynchronizedValueFactory<Long> getNonceFactory() { // No private API implemented. Not needed for this exchange at the moment. return null; } @Override public void remoteInit() throws IOException, ExchangeException {<FILL_FUNCTION_BODY>} }
BitcoinChartsTicker[] tickers = ((BitcoinChartsMarketDataService) marketDataService).getBitcoinChartsTickers(); exchangeMetaData = BitcoinChartsAdapters.adaptMetaData(exchangeMetaData, tickers); // String json = ObjectMapperHelper.toJSON(exchangeMetaData); // System.out.println("json: " + json);
294
98
392
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.service.account.AccountService getAccountService() ,public List<org.knowm.xchange.instrument.Instrument> getExchangeInstruments() ,public org.knowm.xchange.dto.meta.ExchangeMetaData getExchangeMetaData() ,public org.knowm.xchange.ExchangeSpecification getExchangeSpecification() ,public org.knowm.xchange.service.marketdata.MarketDataService getMarketDataService() ,public java.lang.String getMetaDataFileName(org.knowm.xchange.ExchangeSpecification) ,public SynchronizedValueFactory<java.lang.Long> getNonceFactory() ,public org.knowm.xchange.service.trade.TradeService getTradeService() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException,public java.lang.String toString() <variables>protected org.knowm.xchange.service.account.AccountService accountService,protected org.knowm.xchange.dto.meta.ExchangeMetaData exchangeMetaData,protected org.knowm.xchange.ExchangeSpecification exchangeSpecification,protected final Logger logger,protected org.knowm.xchange.service.marketdata.MarketDataService marketDataService,private final SynchronizedValueFactory<java.lang.Long> nonceFactory,protected org.knowm.xchange.service.trade.TradeService tradeService
knowm_XChange
XChange/xchange-bitcoincore/src/main/java/org/knowm/xchange/bitcoincore/BitcoinCoreAdapters.java
BitcoinCoreAdapters
adaptAccountInfo
class BitcoinCoreAdapters { public static AccountInfo adaptAccountInfo( BitcoinCoreBalanceResponse available, BitcoinCoreBalanceResponse unconfirmed) {<FILL_FUNCTION_BODY>} }
BigDecimal total = available.getAmount().add(unconfirmed.getAmount()); Balance btc = new Balance(Currency.BTC, total, available.getAmount(), unconfirmed.getAmount()); Wallet wallet = Wallet.Builder.from(Arrays.asList(btc)).build(); return new AccountInfo(wallet);
51
89
140
<no_super_class>
knowm_XChange
XChange/xchange-bitcoincore/src/main/java/org/knowm/xchange/bitcoincore/BitcoinCoreWallet.java
BitcoinCoreWallet
getDefaultExchangeSpecification
class BitcoinCoreWallet extends BaseExchange { @Override public ExchangeSpecification getDefaultExchangeSpecification() {<FILL_FUNCTION_BODY>} @Override public void applySpecification(final ExchangeSpecification specification) { if (specification.getPassword() == null) { throw new IllegalStateException("password must be set to enable the wallet's RPC interface"); } super.applySpecification(specification); } @Override protected void initServices() { this.accountService = new BitcoinCoreAccountService(this); } @Override public void remoteInit() throws IOException, ExchangeException { // there is no remote init } @Override public SynchronizedValueFactory<Long> getNonceFactory() { throw new UnsupportedOperationException("not applicable"); } }
ExchangeSpecification specification = new ExchangeSpecification(this.getClass()); specification.setShouldLoadRemoteMetaData(false); specification.setPlainTextUri("http://localhost:8332/"); specification.setExchangeName("BitcoinCore"); specification.setExchangeDescription("BitcoinCore wallet"); return specification;
214
85
299
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.service.account.AccountService getAccountService() ,public List<org.knowm.xchange.instrument.Instrument> getExchangeInstruments() ,public org.knowm.xchange.dto.meta.ExchangeMetaData getExchangeMetaData() ,public org.knowm.xchange.ExchangeSpecification getExchangeSpecification() ,public org.knowm.xchange.service.marketdata.MarketDataService getMarketDataService() ,public java.lang.String getMetaDataFileName(org.knowm.xchange.ExchangeSpecification) ,public SynchronizedValueFactory<java.lang.Long> getNonceFactory() ,public org.knowm.xchange.service.trade.TradeService getTradeService() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException,public java.lang.String toString() <variables>protected org.knowm.xchange.service.account.AccountService accountService,protected org.knowm.xchange.dto.meta.ExchangeMetaData exchangeMetaData,protected org.knowm.xchange.ExchangeSpecification exchangeSpecification,protected final Logger logger,protected org.knowm.xchange.service.marketdata.MarketDataService marketDataService,private final SynchronizedValueFactory<java.lang.Long> nonceFactory,protected org.knowm.xchange.service.trade.TradeService tradeService
knowm_XChange
XChange/xchange-bitcoincore/src/main/java/org/knowm/xchange/bitcoincore/service/BitcoinCoreAccountService.java
BitcoinCoreAccountService
getAccountInfo
class BitcoinCoreAccountService extends BitcoinCoreAccountServiceRaw implements AccountService { public BitcoinCoreAccountService(Exchange exchange) { super(exchange); } @Override public AccountInfo getAccountInfo() throws IOException {<FILL_FUNCTION_BODY>} @Override public TradeHistoryParams createFundingHistoryParams() { throw new NotAvailableFromExchangeException(); } }
final BitcoinCoreBalanceResponse balance = getBalance(); final BitcoinCoreBalanceResponse unconfirmed = getUnconfirmedBalance(); return BitcoinCoreAdapters.adaptAccountInfo(balance, unconfirmed);
106
55
161
<methods>public org.knowm.xchange.bitcoincore.dto.account.BitcoinCoreBalanceResponse getBalance() throws java.io.IOException,public org.knowm.xchange.bitcoincore.dto.account.BitcoinCoreBalanceResponse getUnconfirmedBalance() throws java.io.IOException<variables>private final org.knowm.xchange.bitcoincore.dto.account.BitcoinCoreBalanceRequest balanceRequest,private final non-sealed org.knowm.xchange.bitcoincore.BitcoinCore bitcoinCore,private final org.knowm.xchange.bitcoincore.dto.account.BitcoinCoreUnconfirmedBalanceRequest unconfirmedBalanceRequest
knowm_XChange
XChange/xchange-bitcoinde/src/main/java/org/knowm/xchange/bitcoinde/dto/marketdata/BitcoindeOrderbookWrapper.java
BitcoindeOrderbookWrapper
toString
class BitcoindeOrderbookWrapper extends BitcoindeResponse { private final BitcoindeOrders bitcoindeOrders; public BitcoindeOrderbookWrapper( @JsonProperty("orders") BitcoindeOrders bitcoindeOrders, @JsonProperty("credits") int credits, @JsonProperty("errors") String[] errors) { super(credits, errors); this.bitcoindeOrders = bitcoindeOrders; } public BitcoindeOrders getBitcoindeOrders() { return bitcoindeOrders; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BitcoindeOrderbookWrapper{" + "bitcoindeOrders=" + bitcoindeOrders + "} " + super.toString();
182
49
231
<methods>public void <init>(int, java.lang.String[]) ,public int getCredits() ,public java.lang.String[] getErrors() <variables>private final non-sealed int credits,private final non-sealed java.lang.String[] errors
knowm_XChange
XChange/xchange-bitcoinde/src/main/java/org/knowm/xchange/bitcoinde/v4/dto/trade/BitcoindeMyTrade.java
BitcoindeMyTrade
fromValue
class BitcoindeMyTrade { String tradeId; Boolean isExternalWalletTrade; CurrencyPair tradingPair; BitcoindeType type; BigDecimal amountCurrencyToTrade; BigDecimal amountCurrencyToTradeAfterFee; BigDecimal price; BigDecimal volumeCurrencyToPay; BigDecimal volumeCurrencyToPayAfterFee; BigDecimal feeCurrencyToPay; BigDecimal feeCurrencyToTrade; String newOrderIdForRemainingAmount; State state; Boolean isTradeMarkedAsPaid; Date tradeMarkedAsPaidAt; Rating myRatingForTradingPartner; BitcoindeTradingPartnerInformation tradingPartnerInformation; Date createdAt; Date successfullyFinishedAt; Date cancelledAt; PaymentMethod payment_method; @JsonCreator public BitcoindeMyTrade( @JsonProperty("trade_id") String tradeId, @JsonProperty("is_external_wallet_trade") Boolean isExternalWalletTrade, @JsonProperty("trading_pair") @JsonDeserialize(using = CurrencyPairDeserializer.class) CurrencyPair tradingPair, @JsonProperty("type") BitcoindeType type, @JsonProperty("amount_currency_to_trade") BigDecimal amountCurrencyToTrade, @JsonProperty("amount_currency_to_trade_after_fee") BigDecimal amountCurrencyToTradeAfterFee, @JsonProperty("price") BigDecimal price, @JsonProperty("volume_currency_to_pay") BigDecimal volumeCurrencyToPay, @JsonProperty("volume_currency_to_pay_after_fee") BigDecimal volumeCurrencyToPayAfterFee, @JsonProperty("fee_currency_to_pay") BigDecimal feeCurrencyToPay, @JsonProperty("fee_currency_to_trade") BigDecimal feeCurrencyToTrade, @JsonProperty("new_order_id_for_remaining_amount") String newOrderIdForRemainingAmount, @JsonProperty("state") State state, @JsonProperty("is_trade_marked_as_paid") Boolean isTradeMarkedAsPaid, @JsonProperty("trade_marked_as_paid_at") Date tradeMarkedAsPaidAt, @JsonProperty("my_rating_for_trading_partner") Rating myRatingForTradingPartner, @JsonProperty("trading_partner_information") BitcoindeTradingPartnerInformation tradingPartnerInformation, @JsonProperty("created_at") Date createdAt, @JsonProperty("successfully_finished_at") Date successfullyFinishedAt, @JsonProperty("cancelled_at") Date cancelledAt, @JsonProperty("payment_method") PaymentMethod payment_method) { this.tradeId = tradeId; this.isExternalWalletTrade = isExternalWalletTrade; this.tradingPair = tradingPair; this.type = type; this.amountCurrencyToTrade = amountCurrencyToTrade; this.price = price; this.volumeCurrencyToPay = volumeCurrencyToPay; this.volumeCurrencyToPayAfterFee = volumeCurrencyToPayAfterFee; this.amountCurrencyToTradeAfterFee = amountCurrencyToTradeAfterFee; this.feeCurrencyToPay = feeCurrencyToPay; this.feeCurrencyToTrade = feeCurrencyToTrade; this.newOrderIdForRemainingAmount = newOrderIdForRemainingAmount; this.state = state; this.isTradeMarkedAsPaid = isTradeMarkedAsPaid; this.tradeMarkedAsPaidAt = tradeMarkedAsPaidAt; this.myRatingForTradingPartner = myRatingForTradingPartner; this.tradingPartnerInformation = tradingPartnerInformation; this.createdAt = createdAt; this.successfullyFinishedAt = successfullyFinishedAt; this.cancelledAt = cancelledAt; this.payment_method = payment_method; } public enum State { CANCELLED(-1), PENDING(0), SUCCESSFUL(1); private final int value; State(int value) { this.value = value; } @JsonValue public int getValue() { return value; } @JsonCreator public static State fromValue(final int value) {<FILL_FUNCTION_BODY>} } public enum PaymentMethod { SEPA(1), EXPRESS(2); private final int value; PaymentMethod(int value) { this.value = value; } @JsonValue public int getValue() { return value; } @JsonCreator public static PaymentMethod fromValue(final int value) { for (PaymentMethod paymentMethod : PaymentMethod.values()) { if (value == paymentMethod.getValue()) { return paymentMethod; } } throw new IllegalArgumentException("Unknown BitcoindeMyTrade.PaymentMethod value: " + value); } } public enum Rating { PENDING("pending"), NEGATIVE("negative"), NEUTRAL("neutral"), POSITIVE("positive"); private final String value; Rating(String value) { this.value = value; } @JsonValue public String getValue() { return value; } } }
for (State state : State.values()) { if (value == state.getValue()) { return state; } } throw new IllegalArgumentException("Unknown BitcoindeMyTrade.State value: " + value);
1,449
61
1,510
<no_super_class>
knowm_XChange
XChange/xchange-bitcoinde/src/main/java/org/knowm/xchange/bitcoinde/v4/service/BitcoindeDigest.java
BitcoindeDigest
digestParams
class BitcoindeDigest extends BaseParamsDigest { private final String apiKey; /** * Constructor * * @param secretKeyBase64 * @param apiKey * @throws IllegalArgumentException if key is invalid (cannot be base-64-decoded or the decoded * key is invalid). */ private BitcoindeDigest(String secretKeyBase64, String apiKey) { super(secretKeyBase64, HMAC_SHA_256); this.apiKey = apiKey; } public static BitcoindeDigest createInstance(String secretKeyBase64, String apiKey) { return secretKeyBase64 == null ? null : new BitcoindeDigest(secretKeyBase64, apiKey); } @Override public String digestParams(RestInvocation restInvocation) {<FILL_FUNCTION_BODY>} private String getMD5(String original) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(original.getBytes()); byte[] digest = md.digest(); StringBuffer sb = new StringBuffer(); for (byte b : digest) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); } }
// Step 1: concatenate URL with query string String completeURL = restInvocation.getInvocationUrl(); // Step 2: create md5-Hash of the POST-Parameters for the HMAC-data String httpMethod = restInvocation.getHttpMethod(); String requestBody = restInvocation.getRequestBody(); String md5; if ("POST".equals(httpMethod)) { md5 = getMD5(requestBody); } else { md5 = "d41d8cd98f00b204e9800998ecf8427e"; // no post params for GET methods } // Step 3: concat HMAC-input // http_method+'#'+uri+'#'+api_key+'#'+nonce+'#'+post_parameter_md5_hashed_url_encoded_query_string String nonce = restInvocation.getHttpHeadersFromParams().get("X-API-NONCE"); String hmac_data = String.format("%s#%s#%s#%s#%s", httpMethod, completeURL, apiKey, nonce, md5); // Step 3: Create actual sha256-HMAC Mac mac256 = getMac(); mac256.update(hmac_data.getBytes()); return String.format("%064x", new BigInteger(1, mac256.doFinal()));
375
371
746
<methods>public javax.crypto.Mac getMac() <variables>public static final java.lang.String HMAC_MD5,public static final java.lang.String HMAC_SHA_1,public static final java.lang.String HMAC_SHA_256,public static final java.lang.String HMAC_SHA_384,public static final java.lang.String HMAC_SHA_512,private final non-sealed javax.crypto.Mac mac
knowm_XChange
XChange/xchange-bitcoinde/src/main/java/org/knowm/xchange/bitcoinde/v4/service/BitcoindeOpenOrdersParams.java
BitcoindeOpenOrdersParams
accept
class BitcoindeOpenOrdersParams implements OpenOrdersParamCurrencyPair, OpenOrdersParamOffset { private CurrencyPair currencyPair; private BitcoindeType type; private BitcoindeOrderState state; private Date start; private Date end; private Integer offset; public BitcoindeOpenOrdersParams(final BitcoindeOrderState state) { this.state = state; } @Override public boolean accept(final LimitOrder order) { return accept((Order) order); } @Override public boolean accept(final Order order) {<FILL_FUNCTION_BODY>} }
return order != null && order.getInstrument().equals(currencyPair) && order.getType() == BitcoindeAdapters.adaptOrderType(this.type) && order.getStatus() == BitcoindeAdapters.adaptOrderStatus(this.state) && !order.getTimestamp().before(this.start) && !order.getTimestamp().after(this.end);
170
104
274
<no_super_class>
knowm_XChange
XChange/xchange-bitcoinde/src/main/java/org/knowm/xchange/bitcoinde/v4/service/BitcoindeTradeServiceRaw.java
BitcoindeTradeServiceRaw
getBitcoindeMyOrders
class BitcoindeTradeServiceRaw extends BitcoindeBaseService { private final SynchronizedValueFactory<Long> nonceFactory; protected BitcoindeTradeServiceRaw(BitcoindeExchange exchange) { super(exchange); this.nonceFactory = exchange.getNonceFactory(); } public BitcoindeMyOrdersWrapper getBitcoindeMyOrders( CurrencyPair currencyPair, BitcoindeType type, BitcoindeOrderState state, Date start, Date end, Integer page) throws IOException {<FILL_FUNCTION_BODY>} public BitcoindeResponse bitcoindeCancelOrders(String orderId, CurrencyPair currencyPair) throws IOException { try { String currPair = createBitcoindePair(currencyPair); return bitcoinde.deleteOrder(apiKey, nonceFactory, signatureCreator, orderId, currPair); } catch (BitcoindeException e) { throw handleError(e); } } public BitcoindeIdResponse bitcoindePlaceLimitOrder(LimitOrder order) throws IOException { try { String side = createBitcoindeType(order.getType()); String bitcoindeCurrencyPair = createBitcoindePair(order.getCurrencyPair()); return bitcoinde.createOrder( apiKey, nonceFactory, signatureCreator, order.getOriginalAmount(), order.getLimitPrice(), bitcoindeCurrencyPair, side); } catch (BitcoindeException e) { throw handleError(e); } } /** * Calls the API function Bitcoinde.getMyTrades(). * * @param tradingPair optional (default: all) * @param type optional (default: all) * @param state optional (default: all) * @param actionRequired (default: all) * @param paymentMethod (default: all) * @param start optional (default: 10 days ago) * @param end optional (default: yesterday) * @param page optional (default: 1) * @return BitcoindeAccountLedgerWrapper * @throws IOException */ public BitcoindeMyTradesWrapper getBitcoindeMyTrades( CurrencyPair tradingPair, BitcoindeType type, BitcoindeMyTrade.State state, Boolean actionRequired, BitcoindeMyTrade.PaymentMethod paymentMethod, Date start, Date end, Integer page) throws IOException { String typeAsString = type != null ? type.getValue() : null; Integer stateAsInteger = state != null ? state.getValue() : null; Integer actionRequiredAsInteger = actionRequired != null ? createBitcoindeBoolean(actionRequired) : null; Integer paymentMethodeAsInteger = paymentMethod != null ? paymentMethod.getValue() : null; String startAsString = start != null ? rfc3339Timestamp(start) : null; String endAsString = end != null ? rfc3339Timestamp(end) : null; try { if (tradingPair == null) { return bitcoinde.getMyTrades( apiKey, nonceFactory, signatureCreator, typeAsString, stateAsInteger, actionRequiredAsInteger, paymentMethodeAsInteger, startAsString, endAsString, page); } return bitcoinde.getMyTrades( apiKey, nonceFactory, signatureCreator, createBitcoindePair(tradingPair), typeAsString, stateAsInteger, actionRequiredAsInteger, paymentMethodeAsInteger, startAsString, endAsString, page); } catch (BitcoindeException e) { throw handleError(e); } } }
try { String typeAsString = type != null ? type.getValue() : null; Integer stateAsInteger = state != null ? state.getValue() : null; String startAsString = start != null ? rfc3339Timestamp(start) : null; String endAsString = end != null ? rfc3339Timestamp(end) : null; if (currencyPair == null) { return bitcoinde.getMyOrders( apiKey, nonceFactory, signatureCreator, typeAsString, stateAsInteger, startAsString, endAsString, page); } return bitcoinde.getMyOrders( apiKey, nonceFactory, signatureCreator, createBitcoindePair(currencyPair), typeAsString, stateAsInteger, startAsString, endAsString, page); } catch (BitcoindeException e) { throw handleError(e); }
1,023
262
1,285
<methods><variables>protected final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.bitcoinde.v4.Bitcoinde bitcoinde,protected final non-sealed org.knowm.xchange.bitcoinde.v4.service.BitcoindeDigest signatureCreator
knowm_XChange
XChange/xchange-bitcointoyou/src/main/java/org/knowm/xchange/bitcointoyou/dto/marketdata/BitcointoyouMarketData.java
BitcointoyouMarketData
toString
class BitcointoyouMarketData { private final BigDecimal high; private final BigDecimal low; private final BigDecimal volume; private final BigDecimal last; private final BigDecimal buy; private final BigDecimal buyQuantity; private final BigDecimal sell; private final BigDecimal sellQuantity; private final Long date; @JsonIgnore private final Map<String, Object> additionalProperties = new HashMap<>(); public BitcointoyouMarketData( @JsonProperty("high") BigDecimal high, @JsonProperty("low") BigDecimal low, @JsonProperty("vol") BigDecimal volume, @JsonProperty("last") BigDecimal last, @JsonProperty("buy") BigDecimal buy, @JsonProperty("buyQty") BigDecimal buyQuantity, @JsonProperty("sell") BigDecimal sell, @JsonProperty("sellQty") BigDecimal sellQuantity, @JsonProperty("date") Long date) { this.high = high; this.low = low; this.volume = volume; this.last = last; this.buy = buy; this.buyQuantity = buyQuantity; this.sell = sell; this.sellQuantity = sellQuantity; this.date = date; } public BigDecimal getHigh() { return high; } public BigDecimal getLow() { return low; } public BigDecimal getVolume() { return volume; } public BigDecimal getLast() { return last; } public BigDecimal getBuy() { return buy; } public BigDecimal getBuyQuantity() { return buyQuantity; } public BigDecimal getSell() { return sell; } public BigDecimal getSellQuantity() { return sellQuantity; } public Long getDate() { return date; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return String.format( "BitcointoyouMarketData [high=%f, low=%f, volume=%f, last=%f, buy=%f, buyQuantity=%f, sell=%f, " + "sellQuantity=%f, additionalProperties=%s]", high, low, volume, last, buy, buyQuantity, sell, sellQuantity, date);
635
103
738
<no_super_class>
knowm_XChange
XChange/xchange-bitcointoyou/src/main/java/org/knowm/xchange/bitcointoyou/service/polling/BitcointoyouAccountServiceRaw.java
BitcointoyouAccountServiceRaw
getWallets
class BitcointoyouAccountServiceRaw extends BitcointoyouBasePollingService { /** * Constructor * * @param exchange the Bitcointoyou Exchange */ BitcointoyouAccountServiceRaw(Exchange exchange) { super(exchange); } List<Balance> getWallets() {<FILL_FUNCTION_BODY>} }
try { BitcointoyouBalance response = bitcointoyouAuthenticated.returnBalances( apiKey, exchange.getNonceFactory(), signatureCreator); return BitcointoyouAdapters.adaptBitcointoyouBalances(response); } catch (BitcointoyouException e) { throw new ExchangeException(e.getError()); }
103
102
205
<methods><variables>final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.bitcointoyou.Bitcointoyou bitcointoyou,final non-sealed org.knowm.xchange.bitcointoyou.BitcointoyouAuthenticated bitcointoyouAuthenticated,final non-sealed ParamsDigest signatureCreator
knowm_XChange
XChange/xchange-bitcointoyou/src/main/java/org/knowm/xchange/bitcointoyou/service/polling/BitcointoyouMarketDataServiceRaw.java
BitcointoyouMarketDataServiceRaw
getBitcointoyouPublicTrades
class BitcointoyouMarketDataServiceRaw extends BitcointoyouBasePollingService { /** * Constructor * * @param exchange the Bitcointoyou Exchange */ BitcointoyouMarketDataServiceRaw(Exchange exchange) { super(exchange); } BitcointoyouTicker getBitcointoyouTicker(CurrencyPair currencyPair) throws IOException { Map<String, BitcointoyouMarketData> marketData; try { marketData = bitcointoyou.getTicker(); } catch (BitcointoyouException e) { throw new ExchangeException(e.getError()); } BitcointoyouMarketData data = null; if (marketData != null && !marketData.isEmpty()) { data = marketData.entrySet().iterator().next().getValue(); } if (data == null) throw new ExchangeException(currencyPair + " not available"); return new BitcointoyouTicker(data, currencyPair); } BitcointoyouOrderBook getBitcointoyouOrderBook() throws IOException { try { return bitcointoyou.getOrderBook(); } catch (BitcointoyouException e) { throw new ExchangeException(e.getMessage(), e); } } /** * List all public trades made at Bitcointoyou Exchange. * * @param currencyPair the trade currency pair * @return an array of {@link BitcointoyouPublicTrade} * @throws IOException */ BitcointoyouPublicTrade[] getBitcointoyouPublicTrades(CurrencyPair currencyPair) throws IOException { try { return getBitcointoyouPublicTrades(currencyPair, null, null); } catch (BitcointoyouException e) { throw new ExchangeException(e.getError()); } } /** * List all public trades made at Bitcointoyou Exchange. * * @param currencyPair the trade currency pair * @param tradeTimestamp the trade timestamp * @param minTradeId the minimum trade ID * @return an array of {@link BitcointoyouPublicTrade} * @throws IOException */ BitcointoyouPublicTrade[] getBitcointoyouPublicTrades( CurrencyPair currencyPair, Long tradeTimestamp, Long minTradeId) throws IOException {<FILL_FUNCTION_BODY>} }
String currency = currencyPair.base.toString(); try { return bitcointoyou.getTrades(currency, tradeTimestamp, minTradeId); } catch (BitcointoyouException e) { throw new ExchangeException(e.getError()); }
633
73
706
<methods><variables>final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.bitcointoyou.Bitcointoyou bitcointoyou,final non-sealed org.knowm.xchange.bitcointoyou.BitcointoyouAuthenticated bitcointoyouAuthenticated,final non-sealed ParamsDigest signatureCreator
knowm_XChange
XChange/xchange-bitcointoyou/src/main/java/org/knowm/xchange/bitcointoyou/service/polling/BitcointoyouTradeServiceRaw.java
BitcointoyouTradeServiceRaw
cancel
class BitcointoyouTradeServiceRaw extends BitcointoyouBasePollingService { /** * Constructor * * @param exchange the Bitcointoyou Exchange */ public BitcointoyouTradeServiceRaw(Exchange exchange) { super(exchange); } public BitcointoyouOrderResponse returnOpenOrders() throws IOException { return bitcointoyouAuthenticated.returnOpenOrders( apiKey, exchange.getNonceFactory(), signatureCreator); } public BitcointoyouOrderResponse returnOrderById(String orderId) throws IOException { return bitcointoyouAuthenticated.returnOrderById( apiKey, exchange.getNonceFactory(), signatureCreator, orderId); } public BitcointoyouOrderResponse buy(LimitOrder limitOrder) throws IOException { return createOrder("buy", limitOrder); } public BitcointoyouOrderResponse sell(LimitOrder limitOrder) throws IOException { return createOrder("sell", limitOrder); } private BitcointoyouOrderResponse createOrder(String action, LimitOrder limitOrder) throws IOException { try { String asset = limitOrder.getCurrencyPair().base.getSymbol(); return bitcointoyouAuthenticated.createOrder( apiKey, exchange.getNonceFactory(), signatureCreator, asset, action, limitOrder.getOriginalAmount(), limitOrder.getLimitPrice()); } catch (BitcointoyouException e) { throw new ExchangeException(e.getError()); } } public boolean cancel(String orderId) throws IOException {<FILL_FUNCTION_BODY>} }
/* * No need to look up CurrencyPair associated with orderId, as the caller will provide it. */ HashMap<String, String> response = bitcointoyouAuthenticated.deleteOrder( apiKey, exchange.getNonceFactory(), signatureCreator, orderId); if (response.containsKey("error")) { throw new ExchangeException(response.get("error")); } return response.get("success").equals("1");
441
119
560
<methods><variables>final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.bitcointoyou.Bitcointoyou bitcointoyou,final non-sealed org.knowm.xchange.bitcointoyou.BitcointoyouAuthenticated bitcointoyouAuthenticated,final non-sealed ParamsDigest signatureCreator
knowm_XChange
XChange/xchange-bitfinex/src/main/java/org/knowm/xchange/bitfinex/BitfinexErrorAdapter.java
BitfinexErrorAdapter
adapt
class BitfinexErrorAdapter { private BitfinexErrorAdapter() {} public static ExchangeException adapt(BitfinexException e) {<FILL_FUNCTION_BODY>} }
String message = e.getMessage(); if (StringUtils.isEmpty(message)) { return new ExchangeException(e); } message = message.toLowerCase(); if (message.contains("unknown symbol") || message.contains("symbol: invalid")) { return new CurrencyPairNotValidException(message, e); } else if (message.contains("not enough exchange balance")) { return new FundsExceededException(message, e); } else if (message.contains("err_rate_limit") || message.contains("ratelimit")) { return new RateLimitExceededException(e); } else if (message.contains("nonce")) { return new NonceException(e); } return new ExchangeException(message, e);
52
190
242
<no_super_class>
knowm_XChange
XChange/xchange-bitfinex/src/main/java/org/knowm/xchange/bitfinex/BitfinexExchange.java
BitfinexExchange
remoteInit
class BitfinexExchange extends BaseExchange implements Exchange { private static ResilienceRegistries RESILIENCE_REGISTRIES; private SynchronizedValueFactory<Long> nonceFactory = new AtomicLongIncrementalTime2013NonceFactory(); @Override protected void initServices() { this.marketDataService = new BitfinexMarketDataService(this, getResilienceRegistries()); this.accountService = new BitfinexAccountService(this, getResilienceRegistries()); this.tradeService = new BitfinexTradeService(this, getResilienceRegistries()); } @Override public ResilienceRegistries getResilienceRegistries() { if (RESILIENCE_REGISTRIES == null) { RESILIENCE_REGISTRIES = BitfinexResilience.createRegistries(); } return RESILIENCE_REGISTRIES; } @Override public ExchangeSpecification getDefaultExchangeSpecification() { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass()); exchangeSpecification.setSslUri("https://api.bitfinex.com/"); exchangeSpecification.setHost("api.bitfinex.com"); exchangeSpecification.setPort(80); exchangeSpecification.setExchangeName("BitFinex"); exchangeSpecification.setExchangeDescription("BitFinex is a bitcoin exchange."); exchangeSpecification.getResilience().setRateLimiterEnabled(true); exchangeSpecification.getResilience().setRetryEnabled(true); return exchangeSpecification; } @Override public SynchronizedValueFactory<Long> getNonceFactory() { return nonceFactory; } @Override public void remoteInit() throws IOException, ExchangeException {<FILL_FUNCTION_BODY>} }
try { BitfinexMarketDataServiceRaw dataService = (BitfinexMarketDataServiceRaw) this.marketDataService; List<CurrencyPair> currencyPairs = dataService.getExchangeSymbols(); exchangeMetaData = BitfinexAdapters.adaptMetaData(currencyPairs, exchangeMetaData); // Get the last-price of each pair. It is needed to infer XChange's priceScale out of // Bitfinex's pricePercision Map<CurrencyPair, BigDecimal> lastPrices = Arrays.stream(dataService.getBitfinexTickers(null)) .map(BitfinexAdapters::adaptTicker) .collect(Collectors.toMap(t -> t.getCurrencyPair(), t -> t.getLast())); final List<BitfinexSymbolDetail> symbolDetails = dataService.getSymbolDetails(); exchangeMetaData = BitfinexAdapters.adaptMetaData(exchangeMetaData, symbolDetails, lastPrices); if (exchangeSpecification.getApiKey() != null && exchangeSpecification.getSecretKey() != null) { // Bitfinex does not provide any specific wallet health info // So instead of wallet status, fetch platform status to get wallet health Integer bitfinexPlatformStatusData = dataService.getBitfinexPlatformStatus()[0]; boolean bitfinexPlatformStatusPresent = bitfinexPlatformStatusData != null; int bitfinexPlatformStatus = bitfinexPlatformStatusPresent ? bitfinexPlatformStatusData : 0; // Additional remoteInit configuration for authenticated instances BitfinexAccountService accountService = (BitfinexAccountService) this.accountService; final BitfinexAccountFeesResponse accountFees = accountService.getAccountFees(); exchangeMetaData = BitfinexAdapters.adaptMetaData( accountFees, bitfinexPlatformStatus, bitfinexPlatformStatusPresent, exchangeMetaData); BitfinexTradeService tradeService = (BitfinexTradeService) this.tradeService; final BitfinexAccountInfosResponse[] bitfinexAccountInfos = tradeService.getBitfinexAccountInfos(); exchangeMetaData = BitfinexAdapters.adaptMetaData(bitfinexAccountInfos, exchangeMetaData); } } catch (BitfinexException e) { throw BitfinexErrorAdapter.adapt(e); }
494
641
1,135
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.service.account.AccountService getAccountService() ,public List<org.knowm.xchange.instrument.Instrument> getExchangeInstruments() ,public org.knowm.xchange.dto.meta.ExchangeMetaData getExchangeMetaData() ,public org.knowm.xchange.ExchangeSpecification getExchangeSpecification() ,public org.knowm.xchange.service.marketdata.MarketDataService getMarketDataService() ,public java.lang.String getMetaDataFileName(org.knowm.xchange.ExchangeSpecification) ,public SynchronizedValueFactory<java.lang.Long> getNonceFactory() ,public org.knowm.xchange.service.trade.TradeService getTradeService() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException,public java.lang.String toString() <variables>protected org.knowm.xchange.service.account.AccountService accountService,protected org.knowm.xchange.dto.meta.ExchangeMetaData exchangeMetaData,protected org.knowm.xchange.ExchangeSpecification exchangeSpecification,protected final Logger logger,protected org.knowm.xchange.service.marketdata.MarketDataService marketDataService,private final SynchronizedValueFactory<java.lang.Long> nonceFactory,protected org.knowm.xchange.service.trade.TradeService tradeService
knowm_XChange
XChange/xchange-bitfinex/src/main/java/org/knowm/xchange/bitfinex/v1/BitfinexUtils.java
BitfinexUtils
convertToBitfinexWithdrawalType
class BitfinexUtils { /** private Constructor */ private BitfinexUtils() {} private static final String USDT_SYMBOL_BITFINEX = "UST"; private static final String USDT_SYMBOL_XCHANGE = "USDT"; public static String adaptXchangeCurrency(Currency xchangeSymbol) { if (xchangeSymbol == null) { return null; } if (USDT_SYMBOL_XCHANGE.equals(xchangeSymbol.toString())) { return USDT_SYMBOL_BITFINEX; } return xchangeSymbol.toString(); // .toLowerCase(); } public static String toPairString(CurrencyPair currencyPair) { if (currencyPair == null) { return null; } String base = adaptXchangeCurrency(currencyPair.base); String counter = adaptXchangeCurrency(currencyPair.counter); return "t" + base + currencySeparator(base, counter) + adaptXchangeCurrency(currencyPair.counter); } public static String toPairStringV1(CurrencyPair currencyPair) { if (currencyPair == null) { return null; } String base = StringUtils.lowerCase(adaptXchangeCurrency(currencyPair.base)); String counter = StringUtils.lowerCase(adaptXchangeCurrency(currencyPair.counter)); return base + currencySeparator(base, counter) + adaptXchangeCurrency(currencyPair.counter); } /** * Unfortunately we need to go this way, since the pairs at Bitfinex are not very consistent see * dusk:xxx pairs at https://api.bitfinex.com/v1/symbols_details the same for xxx:cnht * * @param base currency to build string with * @param counter currency to build string with * @return string based on pair */ private static String currencySeparator(String base, String counter) { if (base.length() > 3 || counter.length() > 3) { return ":"; } return ""; } /** * From the reference documentation for field withdraw_type (2018-02-14); can be one of the * following ['bitcoin', 'litecoin', 'ethereum', 'ethereumc', 'mastercoin', 'zcash', 'monero', * 'wire', 'dash', 'ripple', 'eos', 'neo', 'aventus', 'qtum', 'eidoo'] From customer support via * email on 2018-02-27; "... After discussing with our developers, you can use API to withdraw BCH * and withdraw_type is bcash. ..." * * @param currency * @return */ public static String convertToBitfinexWithdrawalType(String currency) {<FILL_FUNCTION_BODY>} }
switch (currency.toUpperCase()) { case "BTC": return "bitcoin"; case "LTC": return "litecoin"; case "ETH": return "ethereum"; case "ETC": return "ethereumc"; case "CLO": return "clo"; case "ZEC": return "zcash"; case "XMR": return "monero"; case "USD": return "mastercoin"; case "DASH": return "dash"; case "XRP": return "ripple"; case "EOS": return "eos"; case "NEO": return "neo"; case "AVT": return "aventus"; case "QTUM": return "qtum"; case "EDO": return "eidoo"; case "BTG": return "bgold"; case "BCH": return "bcash"; case "USDT": return "tetheruso"; default: throw new ExchangeException("Cannot determine withdrawal type."); }
746
296
1,042
<no_super_class>
knowm_XChange
XChange/xchange-bitfinex/src/main/java/org/knowm/xchange/bitfinex/v1/dto/account/BitfinexMarginLimit.java
BitfinexMarginLimit
toString
class BitfinexMarginLimit { @JsonProperty("on_pair") private String onPair; @JsonProperty("initial_margin") private BigDecimal initialMargin; @JsonProperty("margin_requirement") private BigDecimal marginRequirement; @JsonProperty("tradable_balance") private BigDecimal tradableBalance; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("on_pair") public String getOnPair() { return onPair; } @JsonProperty("on_pair") public void setOnPair(String onPair) { this.onPair = onPair; } @JsonProperty("initial_margin") public BigDecimal getInitialMargin() { return initialMargin; } @JsonProperty("initial_margin") public void setInitialMargin(BigDecimal initialMargin) { this.initialMargin = initialMargin; } @JsonProperty("margin_requirement") public BigDecimal getMarginRequirement() { return marginRequirement; } @JsonProperty("margin_requirement") public void setMarginRequirement(BigDecimal marginRequirement) { this.marginRequirement = marginRequirement; } @JsonProperty("tradable_balance") public BigDecimal getTradableBalance() { return tradableBalance; } @JsonProperty("tradable_balance") public void setTradableBalance(BigDecimal tradableBalance) { this.tradableBalance = tradableBalance; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BitfinexMarginLimit{" + "onPair='" + onPair + '\'' + ", initialMargin=" + initialMargin + ", marginRequirement=" + marginRequirement + ", tradableBalance=" + tradableBalance + '}';
542
86
628
<no_super_class>
knowm_XChange
XChange/xchange-bitfinex/src/main/java/org/knowm/xchange/bitfinex/v1/dto/trade/BitfinexAccountInfosResponse.java
BitfinexAccountInfosResponse
toString
class BitfinexAccountInfosResponse { private final BigDecimal makerFees; private final BigDecimal takerFees; private final BitfinexFee[] fees; public BitfinexAccountInfosResponse( @JsonProperty("maker_fees") BigDecimal makerFees, @JsonProperty("taker_fees") BigDecimal takerFees, @JsonProperty("fees") BitfinexFee[] fees) { this.makerFees = makerFees; this.takerFees = takerFees; this.fees = fees; } @Override public String toString() {<FILL_FUNCTION_BODY>} public BigDecimal getMakerFees() { return makerFees; } public BigDecimal getTakerFees() { return takerFees; } public BitfinexFee[] getFees() { return fees; } }
StringBuilder builder = new StringBuilder(); builder.append("BitfinexAccountInfosResponse [makerFees="); builder.append(makerFees); builder.append(", takerFees="); builder.append(takerFees); builder.append("]"); return builder.toString();
256
83
339
<no_super_class>
knowm_XChange
XChange/xchange-bitfinex/src/main/java/org/knowm/xchange/bitfinex/v1/dto/trade/BitfinexActivePositionsResponse.java
BitfinexActivePositionsResponse
toString
class BitfinexActivePositionsResponse { private final long id; private final String symbol; private final String status; private final BigDecimal base; private final BigDecimal amount; private final BigDecimal timestamp; private final BigDecimal swap; private final BigDecimal pnl; private final OrderType orderType; public BitfinexActivePositionsResponse( @JsonProperty("id") long id, @JsonProperty("symbol") String symbol, @JsonProperty("status") String status, @JsonProperty("base") BigDecimal base, @JsonProperty("amount") BigDecimal amount, @JsonProperty("timestamp") BigDecimal timestamp, @JsonProperty("swap") BigDecimal swap, @JsonProperty("pl") BigDecimal pnl) { this.id = id; this.symbol = symbol; this.status = status; this.base = base; this.amount = amount; this.timestamp = timestamp; this.swap = swap; this.pnl = pnl; this.orderType = amount.signum() < 0 ? OrderType.ASK : OrderType.BID; } public long getId() { return id; } public String getSymbol() { return symbol; } public String getStatus() { return status; } public BigDecimal getBase() { return base; } public BigDecimal getAmount() { return amount; } public BigDecimal getTimestamp() { return timestamp; } public BigDecimal getSwap() { return swap; } public BigDecimal getPnl() { return pnl; } public OrderType getOrderType() { return orderType; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder builder = new StringBuilder(); builder.append("BitfinexActivePositionsResponse [id="); builder.append(id); builder.append(", symbol="); builder.append(symbol); builder.append(", status="); builder.append(status); builder.append(", base="); builder.append(base); builder.append(", amount="); builder.append(amount); builder.append(", timestamp="); builder.append(timestamp); builder.append(", swap="); builder.append(swap); builder.append(", pnl="); builder.append(pnl); builder.append(", orderType="); builder.append(orderType); builder.append("]"); return builder.toString();
503
203
706
<no_super_class>
knowm_XChange
XChange/xchange-bitfinex/src/main/java/org/knowm/xchange/bitfinex/v1/dto/trade/BitfinexFundingTradeResponse.java
BitfinexFundingTradeResponse
toString
class BitfinexFundingTradeResponse { private final BigDecimal rate; private final BigDecimal period; private final BigDecimal amount; private final BigDecimal timestamp; private final String type; private final String tradeId; private final String offerId; /** * Constructor * * @param rate * @param amount * @param timestamp * @param period * @param type * @param tradeId * @param offerId */ public BitfinexFundingTradeResponse( @JsonProperty("rate") final BigDecimal rate, @JsonProperty("period") final BigDecimal period, @JsonProperty("amount") final BigDecimal amount, @JsonProperty("timestamp") final BigDecimal timestamp, @JsonProperty("type") final String type, @JsonProperty("tid") final String tradeId, @JsonProperty("offer_id") final String offerId) { this.rate = rate; this.amount = amount; this.period = period; this.timestamp = timestamp; this.type = type; this.tradeId = tradeId; this.offerId = offerId; } public BigDecimal getRate() { return rate; } public BigDecimal getPeriod() { return period; } public BigDecimal getAmount() { return amount; } public BigDecimal getTimestamp() { return timestamp; } public String getType() { return type; } public String getTradeId() { return tradeId; } public String getOfferId() { return offerId; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BitfinexFundingTradeResponse [rate=" + rate + ", period=" + period + ", amount=" + amount + ", timestamp=" + timestamp + ", type=" + type + ", tradeId=" + tradeId + ", offerId=" + offerId + "]";
471
101
572
<no_super_class>
knowm_XChange
XChange/xchange-bitfinex/src/main/java/org/knowm/xchange/bitfinex/v1/dto/trade/BitfinexOrderStatusResponse.java
BitfinexOrderStatusResponse
toString
class BitfinexOrderStatusResponse { private final long id; private final String symbol; private final BigDecimal price; private final BigDecimal avgExecutionPrice; private final String side; private final String type; private final BigDecimal timestamp; private final boolean isLive; private final boolean isCancelled; private final boolean wasForced; private final BigDecimal originalAmount; private final BigDecimal remainingAmount; private final BigDecimal executedAmount; /** * Constructor * * @param id * @param symbol * @param price * @param avgExecutionPrice * @param side * @param type * @param timestamp * @param isLive * @param isCancelled * @param wasForced * @param originalAmount * @param remainingAmount * @param executedAmount */ public BitfinexOrderStatusResponse( @JsonProperty("order_id") long id, @JsonProperty("symbol") String symbol, @JsonProperty("price") BigDecimal price, @JsonProperty("avg_execution_price") BigDecimal avgExecutionPrice, @JsonProperty("side") String side, @JsonProperty("type") String type, @JsonProperty("timestamp") BigDecimal timestamp, @JsonProperty("is_live") boolean isLive, @JsonProperty("is_cancelled") boolean isCancelled, @JsonProperty("was_forced") boolean wasForced, @JsonProperty("original_amount") BigDecimal originalAmount, @JsonProperty("remaining_amount") BigDecimal remainingAmount, @JsonProperty("executed_amount") BigDecimal executedAmount) { this.id = id; this.symbol = symbol; this.price = price; this.avgExecutionPrice = avgExecutionPrice; this.side = side; this.type = type; this.timestamp = timestamp; this.isLive = isLive; this.isCancelled = isCancelled; this.wasForced = wasForced; this.originalAmount = originalAmount; this.remainingAmount = remainingAmount; this.executedAmount = executedAmount; } public BigDecimal getExecutedAmount() { return executedAmount; } public BigDecimal getRemainingAmount() { return remainingAmount; } public BigDecimal getOriginalAmount() { return originalAmount; } public boolean getWasForced() { return wasForced; } public String getType() { return type; } public String getSymbol() { return symbol; } public boolean isCancelled() { return isCancelled; } public BigDecimal getPrice() { return price; } public String getSide() { return side; } public BigDecimal getTimestamp() { return timestamp; } public long getId() { return id; } public boolean isLive() { return isLive; } public BigDecimal getAvgExecutionPrice() { return avgExecutionPrice; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder builder = new StringBuilder(); builder.append("BitfinexOrderStatusResponse [id="); builder.append(id); builder.append(", symbol="); builder.append(symbol); builder.append(", price="); builder.append(price); builder.append(", avgExecutionPrice="); builder.append(avgExecutionPrice); builder.append(", side="); builder.append(side); builder.append(", type="); builder.append(type); builder.append(", timestamp="); builder.append(timestamp); builder.append(", isLive="); builder.append(isLive); builder.append(", isCancelled="); builder.append(isCancelled); builder.append(", wasForced="); builder.append(wasForced); builder.append(", originalAmount="); builder.append(originalAmount); builder.append(", remainingAmount="); builder.append(remainingAmount); builder.append(", executedAmount="); builder.append(executedAmount); builder.append("]"); return builder.toString();
864
296
1,160
<no_super_class>
knowm_XChange
XChange/xchange-bitflyer/src/main/java/org/knowm/xchange/bitflyer/dto/account/BitflyerDepositOrWithdrawal.java
BitflyerDepositOrWithdrawal
toString
class BitflyerDepositOrWithdrawal extends BitflyerBaseHistoryResponse { @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BitflyerCashDeposit [id=" + id + ", orderID=" + orderID + ", currencyCode=" + currencyCode + ", amount=" + amount + ", status=" + status + ", eventDate=" + eventDate + "]";
47
90
137
<methods>public non-sealed void <init>() ,public java.math.BigDecimal getAmount() ,public java.lang.String getCurrencyCode() ,public java.lang.String getEventDate() ,public java.lang.String getID() ,public java.lang.String getOrderID() ,public java.lang.String getStatus() ,public void setAmount(java.math.BigDecimal) ,public void setCurrencyCode(java.lang.String) ,public void setEventDate(java.lang.String) ,public void setID(java.lang.String) ,public void setOrderID(java.lang.String) ,public void setStatus(java.lang.String) <variables>java.math.BigDecimal amount,java.lang.String currencyCode,java.lang.String eventDate,java.lang.String id,java.lang.String orderID,java.lang.String status
knowm_XChange
XChange/xchange-bitflyer/src/main/java/org/knowm/xchange/bitflyer/dto/account/BitflyerMarginStatus.java
BitflyerMarginStatus
toString
class BitflyerMarginStatus { @JsonProperty("collateral") private BigDecimal collateral; @JsonProperty("open_position_pnl") private BigDecimal openPositionPnl; @JsonProperty("require_collateral") private BigDecimal requireCollateral; @JsonProperty("keep_rate") private BigDecimal keepRate; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<>(); public BigDecimal getCollateral() { return collateral; } public void setCollateral(BigDecimal collateral) { this.collateral = collateral; } public BigDecimal getOpenPositionPnl() { return openPositionPnl; } public void setOpenPositionPnl(BigDecimal openPositionPnl) { this.openPositionPnl = openPositionPnl; } public BigDecimal getRequireCollateral() { return requireCollateral; } public void setRequireCollateral(BigDecimal requireCollateral) { this.requireCollateral = requireCollateral; } public BigDecimal getKeepRate() { return keepRate; } public void setKeepRate(BigDecimal keepRate) { this.keepRate = keepRate; } public Map<String, Object> getAdditionalProperties() { return additionalProperties; } public void setAdditionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BitflyerMarginStatus{" + "collateral=" + collateral + ", openPositionPnl=" + openPositionPnl + ", requireCollateral=" + requireCollateral + ", keepRate=" + keepRate + ", additionalProperties=" + additionalProperties + '}';
429
94
523
<no_super_class>