id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
36,900
profesorfalken/WMI4Java
src/main/java/com/profesorfalken/wmi4java/WMI4Java.java
WMI4Java.listProperties
public List<String> listProperties(String wmiClass) throws WMIException { List<String> foundPropertiesList = new ArrayList<String>(); try { String rawData = getWMIStub().listProperties(wmiClass, this.namespace, this.computerName); String[] dataStringLines = rawData.split(NEWLINE_REGEX); for (final String line : dataStringLines) { if (!line.isEmpty()) { foundPropertiesList.add(line.trim()); } } List<String> notAllowed = Arrays.asList(new String[] { "Equals", "GetHashCode", "GetType", "ToString" }); foundPropertiesList.removeAll(notAllowed); } catch (Exception ex) { Logger.getLogger(WMI4Java.class.getName()).log(Level.SEVERE, GENERIC_ERROR_MSG, ex); throw new WMIException(ex); } return foundPropertiesList; }
java
public List<String> listProperties(String wmiClass) throws WMIException { List<String> foundPropertiesList = new ArrayList<String>(); try { String rawData = getWMIStub().listProperties(wmiClass, this.namespace, this.computerName); String[] dataStringLines = rawData.split(NEWLINE_REGEX); for (final String line : dataStringLines) { if (!line.isEmpty()) { foundPropertiesList.add(line.trim()); } } List<String> notAllowed = Arrays.asList(new String[] { "Equals", "GetHashCode", "GetType", "ToString" }); foundPropertiesList.removeAll(notAllowed); } catch (Exception ex) { Logger.getLogger(WMI4Java.class.getName()).log(Level.SEVERE, GENERIC_ERROR_MSG, ex); throw new WMIException(ex); } return foundPropertiesList; }
[ "public", "List", "<", "String", ">", "listProperties", "(", "String", "wmiClass", ")", "throws", "WMIException", "{", "List", "<", "String", ">", "foundPropertiesList", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "try", "{", "String", "raw...
Query a WMI class and return all the available properties @param wmiClass the WMI class to query @return a list with the name of existing properties in the class
[ "Query", "a", "WMI", "class", "and", "return", "all", "the", "available", "properties" ]
a39b153a84a12b0c4c0583234fd2b32aba7f868c
https://github.com/profesorfalken/WMI4Java/blob/a39b153a84a12b0c4c0583234fd2b32aba7f868c/src/main/java/com/profesorfalken/wmi4java/WMI4Java.java#L210-L231
36,901
profesorfalken/WMI4Java
src/main/java/com/profesorfalken/wmi4java/WMI4Java.java
WMI4Java.getRawWMIObjectOutput
public String getRawWMIObjectOutput(String wmiClass) throws WMIException { String rawData; try { if (this.properties != null || this.filters != null) { rawData = getWMIStub().queryObject(wmiClass, this.properties, this.filters, this.namespace, this.computerName); } else { rawData = getWMIStub().listObject(wmiClass, this.namespace, this.computerName); } } catch (WMIException ex) { Logger.getLogger(WMI4Java.class.getName()).log(Level.SEVERE, GENERIC_ERROR_MSG, ex); throw new WMIException(ex); } return rawData; }
java
public String getRawWMIObjectOutput(String wmiClass) throws WMIException { String rawData; try { if (this.properties != null || this.filters != null) { rawData = getWMIStub().queryObject(wmiClass, this.properties, this.filters, this.namespace, this.computerName); } else { rawData = getWMIStub().listObject(wmiClass, this.namespace, this.computerName); } } catch (WMIException ex) { Logger.getLogger(WMI4Java.class.getName()).log(Level.SEVERE, GENERIC_ERROR_MSG, ex); throw new WMIException(ex); } return rawData; }
[ "public", "String", "getRawWMIObjectOutput", "(", "String", "wmiClass", ")", "throws", "WMIException", "{", "String", "rawData", ";", "try", "{", "if", "(", "this", ".", "properties", "!=", "null", "||", "this", ".", "filters", "!=", "null", ")", "{", "raw...
Query all the raw object data for an specific class @param wmiClass string with the name of the class to query @return string with all the properties of the object
[ "Query", "all", "the", "raw", "object", "data", "for", "an", "specific", "class" ]
a39b153a84a12b0c4c0583234fd2b32aba7f868c
https://github.com/profesorfalken/WMI4Java/blob/a39b153a84a12b0c4c0583234fd2b32aba7f868c/src/main/java/com/profesorfalken/wmi4java/WMI4Java.java#L378-L392
36,902
yan74/afplib
org.afplib/src/main/java/org/afplib/io/AfpInputStream.java
AfpInputStream.readStructuredField
public SF readStructuredField() throws IOException { int buf = 0; long thisOffset = offset; if(leadingLengthBytes == -1) { // we haven't tested for mvs download leading length bytes // we don't need them and don't want to see them int leadingLength = 0; do { buf = read(); offset++; leadingLength++; } while((buf & 0xff) != 0x5a && buf != -1 && leadingLength < 5); if((buf & 0xff) != 0x5a) { has5a = false; leadingLength = 1; // so try if byte 3 is 0xd3 -> so this would be an afp without 5a magic byte offset = 2; buf = read(); if(buf == -1) return null; if((buf & 0xff) != 0xd3) { throw new IOException("cannot find 5a magic byte nor d3 -> this is no AFP"); } offset = 0; } leadingLengthBytes = leadingLength-1; // if(buf == -1 && leadingLength > 1) // throw new IOException("found trailing garbage at the end of file."); } else { if(leadingLengthBytes > 0) read(data, 0, leadingLengthBytes); // just throw away those if(has5a) { buf = read(); offset++; } } if(buf == -1) { return null; } if(has5a && (buf & 0xff) != 0x5a) { throw new IOException("cannot find 5a magic byte"); } data[0] = 0x5a; // (byte) (buf & 0xff); buf = read(); offset++; if(buf == -1 && !has5a) { return null; } if(buf == -1) { throw new IOException("premature end of file."); } data[1] = (byte) (buf & 0xff); length = (byte) buf << 8; buf = read(); offset++; if(buf == -1) throw new IOException("premature end of file."); data[2] = (byte) (buf & 0xff); length |= (byte) buf & 0xff; length -= 2; if(length > data.length) throw new IOException("length of structured field is too large: "+length); int read = read(data, 3, length); offset += read; if(read < length) throw new IOException("premature end of file."); SF sf = factory.sf(data, 0, getLength() + 2); sf.setLength(length + 3); sf.setOffset(thisOffset); sf.setNumber(number++); return sf; }
java
public SF readStructuredField() throws IOException { int buf = 0; long thisOffset = offset; if(leadingLengthBytes == -1) { // we haven't tested for mvs download leading length bytes // we don't need them and don't want to see them int leadingLength = 0; do { buf = read(); offset++; leadingLength++; } while((buf & 0xff) != 0x5a && buf != -1 && leadingLength < 5); if((buf & 0xff) != 0x5a) { has5a = false; leadingLength = 1; // so try if byte 3 is 0xd3 -> so this would be an afp without 5a magic byte offset = 2; buf = read(); if(buf == -1) return null; if((buf & 0xff) != 0xd3) { throw new IOException("cannot find 5a magic byte nor d3 -> this is no AFP"); } offset = 0; } leadingLengthBytes = leadingLength-1; // if(buf == -1 && leadingLength > 1) // throw new IOException("found trailing garbage at the end of file."); } else { if(leadingLengthBytes > 0) read(data, 0, leadingLengthBytes); // just throw away those if(has5a) { buf = read(); offset++; } } if(buf == -1) { return null; } if(has5a && (buf & 0xff) != 0x5a) { throw new IOException("cannot find 5a magic byte"); } data[0] = 0x5a; // (byte) (buf & 0xff); buf = read(); offset++; if(buf == -1 && !has5a) { return null; } if(buf == -1) { throw new IOException("premature end of file."); } data[1] = (byte) (buf & 0xff); length = (byte) buf << 8; buf = read(); offset++; if(buf == -1) throw new IOException("premature end of file."); data[2] = (byte) (buf & 0xff); length |= (byte) buf & 0xff; length -= 2; if(length > data.length) throw new IOException("length of structured field is too large: "+length); int read = read(data, 3, length); offset += read; if(read < length) throw new IOException("premature end of file."); SF sf = factory.sf(data, 0, getLength() + 2); sf.setLength(length + 3); sf.setOffset(thisOffset); sf.setNumber(number++); return sf; }
[ "public", "SF", "readStructuredField", "(", ")", "throws", "IOException", "{", "int", "buf", "=", "0", ";", "long", "thisOffset", "=", "offset", ";", "if", "(", "leadingLengthBytes", "==", "-", "1", ")", "{", "// we haven't tested for mvs download leading length b...
Reads a new structured field from the input stream. This method is not thread-safe! @return structured field or null if end of input. @throws IOException
[ "Reads", "a", "new", "structured", "field", "from", "the", "input", "stream", ".", "This", "method", "is", "not", "thread", "-", "safe!" ]
9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f
https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/io/AfpInputStream.java#L58-L143
36,903
yan74/afplib
org.afplib/src/main/java/org/afplib/helper/formdef/FormdefScanner.java
FormdefScanner.scan
public static Formdef scan(AfpInputStream in) throws IOException { Formdef formdef = new FormdefImpl(); SF sf; LinkedList<SF> sfbuffer = null; while((sf = in.readStructuredField()) != null) { log.trace("{}", sf); switch(sf.eClass().getClassifierID()) { case AfplibPackage.ERG: case AfplibPackage.BDT: return null; case AfplibPackage.EFM: return formdef; case AfplibPackage.BDG: sfbuffer = new LinkedList<SF>(); break; case AfplibPackage.EDG: sfbuffer.add(sf); formdef.setBDG((SF[]) sfbuffer.toArray(new SF[sfbuffer.size()])); sfbuffer = null; break; case AfplibPackage.BMM: sfbuffer = new LinkedList<SF>(); break; case AfplibPackage.EMM: sfbuffer.add(sf); formdef.add((SF[]) sfbuffer.toArray(new SF[sfbuffer.size()])); sfbuffer = null; break; } if(sfbuffer != null) sfbuffer.add(sf); } return null; }
java
public static Formdef scan(AfpInputStream in) throws IOException { Formdef formdef = new FormdefImpl(); SF sf; LinkedList<SF> sfbuffer = null; while((sf = in.readStructuredField()) != null) { log.trace("{}", sf); switch(sf.eClass().getClassifierID()) { case AfplibPackage.ERG: case AfplibPackage.BDT: return null; case AfplibPackage.EFM: return formdef; case AfplibPackage.BDG: sfbuffer = new LinkedList<SF>(); break; case AfplibPackage.EDG: sfbuffer.add(sf); formdef.setBDG((SF[]) sfbuffer.toArray(new SF[sfbuffer.size()])); sfbuffer = null; break; case AfplibPackage.BMM: sfbuffer = new LinkedList<SF>(); break; case AfplibPackage.EMM: sfbuffer.add(sf); formdef.add((SF[]) sfbuffer.toArray(new SF[sfbuffer.size()])); sfbuffer = null; break; } if(sfbuffer != null) sfbuffer.add(sf); } return null; }
[ "public", "static", "Formdef", "scan", "(", "AfpInputStream", "in", ")", "throws", "IOException", "{", "Formdef", "formdef", "=", "new", "FormdefImpl", "(", ")", ";", "SF", "sf", ";", "LinkedList", "<", "SF", ">", "sfbuffer", "=", "null", ";", "while", "...
Scans the input for medium maps and adds to the formdef. This scanner will modify the AfpInputStreams position. If you need to keep position, please provide a new AfpInputStream. @param in formdef or afp file to read medium maps from @return formdef in memory representation of the formdef @throws IOException
[ "Scans", "the", "input", "for", "medium", "maps", "and", "adds", "to", "the", "formdef", "." ]
9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f
https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/helper/formdef/FormdefScanner.java#L32-L68
36,904
yan74/afplib
org.afplib/src/main/java/org/afplib/Data.java
Data.decode
public static String decode(String urlString) { StringBuilder s = new StringBuilder(); UrlDecoderState state = UrlDecoderState.INITIAL; int hiNibble = 0; int lowNibble = 0; int length = urlString.length(); for (int i = 0; i < length; i++) { char c = urlString.charAt(i); switch (state) { case INITIAL: if (c == '%') { state = UrlDecoderState.FIRST_HEX; } else { s.append(c); } break; case FIRST_HEX: hiNibble = lookup(c); state = UrlDecoderState.SECOND_HEX; break; case SECOND_HEX: lowNibble = lookup(c); byte b = (byte) ((hiNibble << 4) | lowNibble); s.append((char) b); state = UrlDecoderState.INITIAL; break; } } return s.toString(); }
java
public static String decode(String urlString) { StringBuilder s = new StringBuilder(); UrlDecoderState state = UrlDecoderState.INITIAL; int hiNibble = 0; int lowNibble = 0; int length = urlString.length(); for (int i = 0; i < length; i++) { char c = urlString.charAt(i); switch (state) { case INITIAL: if (c == '%') { state = UrlDecoderState.FIRST_HEX; } else { s.append(c); } break; case FIRST_HEX: hiNibble = lookup(c); state = UrlDecoderState.SECOND_HEX; break; case SECOND_HEX: lowNibble = lookup(c); byte b = (byte) ((hiNibble << 4) | lowNibble); s.append((char) b); state = UrlDecoderState.INITIAL; break; } } return s.toString(); }
[ "public", "static", "String", "decode", "(", "String", "urlString", ")", "{", "StringBuilder", "s", "=", "new", "StringBuilder", "(", ")", ";", "UrlDecoderState", "state", "=", "UrlDecoderState", ".", "INITIAL", ";", "int", "hiNibble", "=", "0", ";", "int", ...
Like java.net.URLDecoder except no conversion of "+" to space
[ "Like", "java", ".", "net", ".", "URLDecoder", "except", "no", "conversion", "of", "+", "to", "space" ]
9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f
https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/Data.java#L304-L333
36,905
yan74/afplib
org.afplib/src/main/java/org/afplib/io/AfpMappedFile.java
AfpMappedFile.next
public SF next() throws IOException { int remaining = afpData.remaining(); if(remaining == 0) return null; if(remaining < 9) throw new IOException("trailing garbage at the end of file."); byte buf; long thisOffset = afpData.position(); try { if(leadingLengthBytes == -1) { // we haven't tested for mvs download leading length bytes // we don't need them and don't want to see them int leadingLength = 0; do { buf = afpData.get(); leadingLength++; } while((buf & 0xff) != 0x5a && afpData.remaining() > 0 && leadingLength < 5); leadingLengthBytes = leadingLength-1; } else { if(leadingLengthBytes > 0) afpData.position(afpData.position() + leadingLengthBytes); // just throw away those buf = afpData.get(); } if((buf & 0xff) != 0x5a) throw new IOException("cannot find 5a magic byte"); data[0] = buf; buf = afpData.get(); data[1] = buf; length = (byte) buf << 8; buf = afpData.get(); data[2] = (byte) (buf & 0xff); length |= (byte) buf & 0xff; length -= 2; if(length + 3 > data.length) throw new IOException("length of structured field is too large: "+length); afpData.get(data, 3, length); } catch (BufferUnderflowException e) { return null; // FIXME could also be an error } SF sf = factory.sf(data, 0, getLength() + 2); sf.setLength(length + 3); sf.setOffset(thisOffset); sf.setNumber(number++); return sf; }
java
public SF next() throws IOException { int remaining = afpData.remaining(); if(remaining == 0) return null; if(remaining < 9) throw new IOException("trailing garbage at the end of file."); byte buf; long thisOffset = afpData.position(); try { if(leadingLengthBytes == -1) { // we haven't tested for mvs download leading length bytes // we don't need them and don't want to see them int leadingLength = 0; do { buf = afpData.get(); leadingLength++; } while((buf & 0xff) != 0x5a && afpData.remaining() > 0 && leadingLength < 5); leadingLengthBytes = leadingLength-1; } else { if(leadingLengthBytes > 0) afpData.position(afpData.position() + leadingLengthBytes); // just throw away those buf = afpData.get(); } if((buf & 0xff) != 0x5a) throw new IOException("cannot find 5a magic byte"); data[0] = buf; buf = afpData.get(); data[1] = buf; length = (byte) buf << 8; buf = afpData.get(); data[2] = (byte) (buf & 0xff); length |= (byte) buf & 0xff; length -= 2; if(length + 3 > data.length) throw new IOException("length of structured field is too large: "+length); afpData.get(data, 3, length); } catch (BufferUnderflowException e) { return null; // FIXME could also be an error } SF sf = factory.sf(data, 0, getLength() + 2); sf.setLength(length + 3); sf.setOffset(thisOffset); sf.setNumber(number++); return sf; }
[ "public", "SF", "next", "(", ")", "throws", "IOException", "{", "int", "remaining", "=", "afpData", ".", "remaining", "(", ")", ";", "if", "(", "remaining", "==", "0", ")", "return", "null", ";", "if", "(", "remaining", "<", "9", ")", "throw", "new",...
Reads a new structured field from the mapped file. This method is not thread-safe! @return structured field or null if end of input. @throws IOException
[ "Reads", "a", "new", "structured", "field", "from", "the", "mapped", "file", ".", "This", "method", "is", "not", "thread", "-", "safe!" ]
9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f
https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/io/AfpMappedFile.java#L45-L99
36,906
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java
BankCardMagneticTrack.from
public static BankCardMagneticTrack from(final String rawTrackData) { final Track1FormatB track1 = Track1FormatB.from(rawTrackData); final Track2 track2 = Track2.from(rawTrackData); final Track3 track3 = Track3.from(rawTrackData); return new BankCardMagneticTrack(rawTrackData, track1, track2, track3); }
java
public static BankCardMagneticTrack from(final String rawTrackData) { final Track1FormatB track1 = Track1FormatB.from(rawTrackData); final Track2 track2 = Track2.from(rawTrackData); final Track3 track3 = Track3.from(rawTrackData); return new BankCardMagneticTrack(rawTrackData, track1, track2, track3); }
[ "public", "static", "BankCardMagneticTrack", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Track1FormatB", "track1", "=", "Track1FormatB", ".", "from", "(", "rawTrackData", ")", ";", "final", "Track2", "track2", "=", "Track2", ".", "from", ...
Parses magnetic track data into a BankCardMagneticTrack object. @param rawTrackData Raw track data as a string. Can include newlines, and all 3 tracks. @return A BankCardMagneticTrack instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "data", "into", "a", "BankCardMagneticTrack", "object", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java#L48-L55
36,907
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java
BankCardMagneticTrack.toBankCard
public BankCard toBankCard() { final AccountNumber pan; if (track1.hasAccountNumber()) { pan = track1.getAccountNumber(); } else { pan = track2.getAccountNumber(); } final Name name; if (track1.hasName()) { name = track1.getName(); } else { name = new Name(); } final ExpirationDate expirationDate; if (track1.hasExpirationDate()) { expirationDate = track1.getExpirationDate(); } else { expirationDate = track2.getExpirationDate(); } final ServiceCode serviceCode; if (track1.hasServiceCode()) { serviceCode = track1.getServiceCode(); } else { serviceCode = track2.getServiceCode(); } final BankCard cardInfo = new BankCard(pan, expirationDate, name, serviceCode); return cardInfo; }
java
public BankCard toBankCard() { final AccountNumber pan; if (track1.hasAccountNumber()) { pan = track1.getAccountNumber(); } else { pan = track2.getAccountNumber(); } final Name name; if (track1.hasName()) { name = track1.getName(); } else { name = new Name(); } final ExpirationDate expirationDate; if (track1.hasExpirationDate()) { expirationDate = track1.getExpirationDate(); } else { expirationDate = track2.getExpirationDate(); } final ServiceCode serviceCode; if (track1.hasServiceCode()) { serviceCode = track1.getServiceCode(); } else { serviceCode = track2.getServiceCode(); } final BankCard cardInfo = new BankCard(pan, expirationDate, name, serviceCode); return cardInfo; }
[ "public", "BankCard", "toBankCard", "(", ")", "{", "final", "AccountNumber", "pan", ";", "if", "(", "track1", ".", "hasAccountNumber", "(", ")", ")", "{", "pan", "=", "track1", ".", "getAccountNumber", "(", ")", ";", "}", "else", "{", "pan", "=", "trac...
Constructs and returns bank card information, if all the track data is consistent. That is, if any bank card information is repeated in track 1 and track 2, it should be the same data. @return Bank card information.
[ "Constructs", "and", "returns", "bank", "card", "information", "if", "all", "the", "track", "data", "is", "consistent", ".", "That", "is", "if", "any", "bank", "card", "information", "is", "repeated", "in", "track", "1", "and", "track", "2", "it", "should"...
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java#L129-L176
36,908
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/BaseBankCardTrackData.java
BaseBankCardTrackData.isConsistentWith
public boolean isConsistentWith(final BaseBankCardTrackData other) { if (this == other) { return true; } if (other == null) { return false; } boolean equals = true; if (hasAccountNumber() && other.hasAccountNumber()) { if (!getAccountNumber().equals(other.getAccountNumber())) { equals = false; } } if (hasExpirationDate() && other.hasExpirationDate()) { if (!getExpirationDate().equals(other.getExpirationDate())) { equals = false; } } if (hasServiceCode() && other.hasServiceCode()) { if (!getServiceCode().equals(other.getServiceCode())) { equals = false; } } return equals; }
java
public boolean isConsistentWith(final BaseBankCardTrackData other) { if (this == other) { return true; } if (other == null) { return false; } boolean equals = true; if (hasAccountNumber() && other.hasAccountNumber()) { if (!getAccountNumber().equals(other.getAccountNumber())) { equals = false; } } if (hasExpirationDate() && other.hasExpirationDate()) { if (!getExpirationDate().equals(other.getExpirationDate())) { equals = false; } } if (hasServiceCode() && other.hasServiceCode()) { if (!getServiceCode().equals(other.getServiceCode())) { equals = false; } } return equals; }
[ "public", "boolean", "isConsistentWith", "(", "final", "BaseBankCardTrackData", "other", ")", "{", "if", "(", "this", "==", "other", ")", "{", "return", "true", ";", "}", "if", "(", "other", "==", "null", ")", "{", "return", "false", ";", "}", "boolean",...
Verifies that the available data is consistent between Track 1 and Track 2, or any other track. @return True if the data is consistent.
[ "Verifies", "that", "the", "available", "data", "is", "consistent", "between", "Track", "1", "and", "Track", "2", "or", "any", "other", "track", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/BaseBankCardTrackData.java#L186-L223
36,909
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/Track1FormatB.java
Track1FormatB.from
public static Track1FormatB from(final String rawTrackData) { final Matcher matcher = track1FormatBPattern .matcher(trimToEmpty(rawTrackData)); final String rawTrack1Data; final AccountNumber pan; final ExpirationDate expirationDate; final Name name; final ServiceCode serviceCode; final String formatCode; final String discretionaryData; if (matcher.matches()) { rawTrack1Data = getGroup(matcher, 1); formatCode = getGroup(matcher, 2); pan = new AccountNumber(getGroup(matcher, 3)); name = new Name(getGroup(matcher, 4)); expirationDate = new ExpirationDate(getGroup(matcher, 5)); serviceCode = new ServiceCode(getGroup(matcher, 6)); discretionaryData = getGroup(matcher, 7); } else { rawTrack1Data = null; formatCode = ""; pan = new AccountNumber(); name = new Name(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track1FormatB(rawTrack1Data, pan, expirationDate, name, serviceCode, formatCode, discretionaryData); }
java
public static Track1FormatB from(final String rawTrackData) { final Matcher matcher = track1FormatBPattern .matcher(trimToEmpty(rawTrackData)); final String rawTrack1Data; final AccountNumber pan; final ExpirationDate expirationDate; final Name name; final ServiceCode serviceCode; final String formatCode; final String discretionaryData; if (matcher.matches()) { rawTrack1Data = getGroup(matcher, 1); formatCode = getGroup(matcher, 2); pan = new AccountNumber(getGroup(matcher, 3)); name = new Name(getGroup(matcher, 4)); expirationDate = new ExpirationDate(getGroup(matcher, 5)); serviceCode = new ServiceCode(getGroup(matcher, 6)); discretionaryData = getGroup(matcher, 7); } else { rawTrack1Data = null; formatCode = ""; pan = new AccountNumber(); name = new Name(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track1FormatB(rawTrack1Data, pan, expirationDate, name, serviceCode, formatCode, discretionaryData); }
[ "public", "static", "Track1FormatB", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Matcher", "matcher", "=", "track1FormatBPattern", ".", "matcher", "(", "trimToEmpty", "(", "rawTrackData", ")", ")", ";", "final", "String", "rawTrack1Data", ...
Parses magnetic track 1 format B data into a Track1FormatB object. @param rawTrackData Raw track data as a string. Can include newlines, and other tracks as well. @return A Track1FormatB instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "1", "format", "B", "data", "into", "a", "Track1FormatB", "object", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/Track1FormatB.java#L78-L119
36,910
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/Track3.java
Track3.from
public static Track3 from(final String rawTrackData) { final Matcher matcher = track3Pattern.matcher(trimToEmpty(rawTrackData)); final String rawTrack3Data; final String discretionaryData; if (matcher.matches()) { rawTrack3Data = getGroup(matcher, 1); discretionaryData = getGroup(matcher, 2); } else { rawTrack3Data = null; discretionaryData = ""; } return new Track3(rawTrack3Data, discretionaryData); }
java
public static Track3 from(final String rawTrackData) { final Matcher matcher = track3Pattern.matcher(trimToEmpty(rawTrackData)); final String rawTrack3Data; final String discretionaryData; if (matcher.matches()) { rawTrack3Data = getGroup(matcher, 1); discretionaryData = getGroup(matcher, 2); } else { rawTrack3Data = null; discretionaryData = ""; } return new Track3(rawTrack3Data, discretionaryData); }
[ "public", "static", "Track3", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Matcher", "matcher", "=", "track3Pattern", ".", "matcher", "(", "trimToEmpty", "(", "rawTrackData", ")", ")", ";", "final", "String", "rawTrack3Data", ";", "final...
Parses magnetic track 3 data into a Track3 object. @param rawTrackData Raw track data as a string. Can include newlines, and other tracks as well. @return A Track3instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "3", "data", "into", "a", "Track3", "object", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/Track3.java#L50-L67
36,911
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/Track2.java
Track2.from
public static Track2 from(final String rawTrackData) { final Matcher matcher = track2Pattern.matcher(trimToEmpty(rawTrackData)); final String rawTrack2Data; final AccountNumber pan; final ExpirationDate expirationDate; final ServiceCode serviceCode; final String discretionaryData; if (matcher.matches()) { rawTrack2Data = getGroup(matcher, 1); pan = new AccountNumber(getGroup(matcher, 2)); expirationDate = new ExpirationDate(getGroup(matcher, 3)); serviceCode = new ServiceCode(getGroup(matcher, 4)); discretionaryData = getGroup(matcher, 5); } else { rawTrack2Data = null; pan = new AccountNumber(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track2(rawTrack2Data, pan, expirationDate, serviceCode, discretionaryData); }
java
public static Track2 from(final String rawTrackData) { final Matcher matcher = track2Pattern.matcher(trimToEmpty(rawTrackData)); final String rawTrack2Data; final AccountNumber pan; final ExpirationDate expirationDate; final ServiceCode serviceCode; final String discretionaryData; if (matcher.matches()) { rawTrack2Data = getGroup(matcher, 1); pan = new AccountNumber(getGroup(matcher, 2)); expirationDate = new ExpirationDate(getGroup(matcher, 3)); serviceCode = new ServiceCode(getGroup(matcher, 4)); discretionaryData = getGroup(matcher, 5); } else { rawTrack2Data = null; pan = new AccountNumber(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track2(rawTrack2Data, pan, expirationDate, serviceCode, discretionaryData); }
[ "public", "static", "Track2", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Matcher", "matcher", "=", "track2Pattern", ".", "matcher", "(", "trimToEmpty", "(", "rawTrackData", ")", ")", ";", "final", "String", "rawTrack2Data", ";", "final...
Parses magnetic track 2 data into a Track2 object. @param rawTrackData Raw track data as a string. Can include newlines, and other tracks as well. @return A Track2 instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "2", "data", "into", "a", "Track2", "object", "." ]
1da8ff20ac6269b1d523875157278978ba71d260
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/Track2.java#L72-L104
36,912
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.ensureRequiredZnodesExist
void ensureRequiredZnodesExist(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { mkdirp(zookeeper, znode); createIfNotThere(zookeeper, QUEUE_NODE); createIfNotThere(zookeeper, POOL_NODE); }
java
void ensureRequiredZnodesExist(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { mkdirp(zookeeper, znode); createIfNotThere(zookeeper, QUEUE_NODE); createIfNotThere(zookeeper, POOL_NODE); }
[ "void", "ensureRequiredZnodesExist", "(", "ZooKeeper", "zookeeper", ",", "String", "znode", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "mkdirp", "(", "zookeeper", ",", "znode", ")", ";", "createIfNotThere", "(", "zookeeper", ",", "QUEUE_NODE...
Make sure the required znodes are present on the quorum. @param zookeeper ZooKeeper connection to use. @param znode Base-path for our znodes.
[ "Make", "sure", "the", "required", "znodes", "are", "present", "on", "the", "quorum", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L93-L97
36,913
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.acquireLock
static String acquireLock(ZooKeeper zookeeper, String lockNode) throws KeeperException, InterruptedException { // Inspired by the queueing algorithm suggested here: // http://zookeeper.apache.org/doc/trunk/recipes.html#sc_recipes_Queues // Acquire a place in the queue by creating an ephemeral, sequential znode. String placeInLine = takeQueueTicket(zookeeper, lockNode); logger.debug("Acquiring lock, waiting in queue: {}.", placeInLine); // Wait in the queue until our turn has come. return waitInLine(zookeeper, lockNode, placeInLine); }
java
static String acquireLock(ZooKeeper zookeeper, String lockNode) throws KeeperException, InterruptedException { // Inspired by the queueing algorithm suggested here: // http://zookeeper.apache.org/doc/trunk/recipes.html#sc_recipes_Queues // Acquire a place in the queue by creating an ephemeral, sequential znode. String placeInLine = takeQueueTicket(zookeeper, lockNode); logger.debug("Acquiring lock, waiting in queue: {}.", placeInLine); // Wait in the queue until our turn has come. return waitInLine(zookeeper, lockNode, placeInLine); }
[ "static", "String", "acquireLock", "(", "ZooKeeper", "zookeeper", ",", "String", "lockNode", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "// Inspired by the queueing algorithm suggested here:", "// http://zookeeper.apache.org/doc/trunk/recipes.html#sc_recipes_...
Try to acquire a lock on for choosing a resource. This method will wait until it has acquired the lock. @param zookeeper ZooKeeper connection to use. @param lockNode Path to the znode representing the locking queue. @return Name of the first node in the queue.
[ "Try", "to", "acquire", "a", "lock", "on", "for", "choosing", "a", "resource", ".", "This", "method", "will", "wait", "until", "it", "has", "acquired", "the", "lock", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L165-L175
36,914
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.takeQueueTicket
static String takeQueueTicket(ZooKeeper zookeeper, String lockNode) throws InterruptedException, KeeperException { // The ticket number includes a random component to decrease the chances of collision. Collision is handled // neatly, but it saves a few actions if there is no need to retry ticket acquisition. String ticket = String.format("nr-%014d-%04d", System.currentTimeMillis(), random.nextInt(10000)); if (grabTicket(zookeeper, lockNode, ticket)) { return ticket; } else { return takeQueueTicket(zookeeper, lockNode); } }
java
static String takeQueueTicket(ZooKeeper zookeeper, String lockNode) throws InterruptedException, KeeperException { // The ticket number includes a random component to decrease the chances of collision. Collision is handled // neatly, but it saves a few actions if there is no need to retry ticket acquisition. String ticket = String.format("nr-%014d-%04d", System.currentTimeMillis(), random.nextInt(10000)); if (grabTicket(zookeeper, lockNode, ticket)) { return ticket; } else { return takeQueueTicket(zookeeper, lockNode); } }
[ "static", "String", "takeQueueTicket", "(", "ZooKeeper", "zookeeper", ",", "String", "lockNode", ")", "throws", "InterruptedException", ",", "KeeperException", "{", "// The ticket number includes a random component to decrease the chances of collision. Collision is handled", "// neat...
Take a ticket for the queue. If the ticket was already claimed by another process, this method retries until it succeeds. @param zookeeper ZooKeeper connection to use. @param lockNode Path to the znode representing the locking queue. @return The claimed ticket.
[ "Take", "a", "ticket", "for", "the", "queue", ".", "If", "the", "ticket", "was", "already", "claimed", "by", "another", "process", "this", "method", "retries", "until", "it", "succeeds", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L185-L194
36,915
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.releaseTicket
static void releaseTicket(ZooKeeper zookeeper, String lockNode, String ticket) throws KeeperException, InterruptedException { logger.debug("Releasing ticket {}.", ticket); try { zookeeper.delete(lockNode + "/" + ticket, -1); } catch (KeeperException e) { if (e.code() != KeeperException.Code.NONODE) { // If it the node is already gone, than that is fine, otherwise: throw e; } } }
java
static void releaseTicket(ZooKeeper zookeeper, String lockNode, String ticket) throws KeeperException, InterruptedException { logger.debug("Releasing ticket {}.", ticket); try { zookeeper.delete(lockNode + "/" + ticket, -1); } catch (KeeperException e) { if (e.code() != KeeperException.Code.NONODE) { // If it the node is already gone, than that is fine, otherwise: throw e; } } }
[ "static", "void", "releaseTicket", "(", "ZooKeeper", "zookeeper", ",", "String", "lockNode", ",", "String", "ticket", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "logger", ".", "debug", "(", "\"Releasing ticket {}.\"", ",", "ticket", ")", "...
Release an acquired lock. @param zookeeper ZooKeeper connection to use. @param lockNode Path to the znode representing the locking queue. @param ticket Name of the first node in the queue.
[ "Release", "an", "acquired", "lock", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L203-L215
36,916
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.waitInLine
static String waitInLine(ZooKeeper zookeeper, String lockNode, String placeInLine) throws KeeperException, InterruptedException { // Get the list of nodes in the queue, and find out what our position is. List<String> children = zookeeper.getChildren(lockNode, false); // The list returned is unsorted. Collections.sort(children); if (children.size() == 0) { // Only possible if some other process cancelled our ticket. logger.warn("getChildren() returned empty list, but we created a ticket."); return acquireLock(zookeeper, lockNode); } boolean lockingTicketExists = children.get(0).equals(LOCKING_TICKET); if (lockingTicketExists) { children.remove(0); } // Where are we in the queue? int positionInQueue = -1; int i = 0; for (String child : children) { if (child.equals(placeInLine)) { positionInQueue = i; break; } i++; } if (positionInQueue < 0) { // Theoretically not possible. throw new RuntimeException("Created node (" + placeInLine + ") not found in getChildren()."); } String placeBeforeUs; if (positionInQueue == 0) { // Lowest number in the queue, go for the lock. if (grabTicket(zookeeper, lockNode, LOCKING_TICKET)) { releaseTicket(zookeeper, lockNode, placeInLine); return LOCKING_TICKET; } else { placeBeforeUs = LOCKING_TICKET; } } else { // We are not in front of the queue, so we keep an eye on the znode right in front of us. When it is // deleted, that means it has reached the front of the queue, acquired the lock, did its business, // and released the lock. placeBeforeUs = children.get(positionInQueue - 1); } final CountDownLatch latch = new CountDownLatch(1); Stat stat = zookeeper.exists(lockNode + "/" + placeBeforeUs, event -> { // If *anything* changes, reevaluate our position in the queue. latch.countDown(); }); // If stat is null, the znode in front of use got deleted during our inspection of the queue. If that happens, // simply reevaluate our position in the queue again. If there *is* a znode in front of us, // watch it for changes: if (stat != null) { logger.debug("Watching place in queue before us ({})", placeBeforeUs); latch.await(); } return waitInLine(zookeeper, lockNode, placeInLine); }
java
static String waitInLine(ZooKeeper zookeeper, String lockNode, String placeInLine) throws KeeperException, InterruptedException { // Get the list of nodes in the queue, and find out what our position is. List<String> children = zookeeper.getChildren(lockNode, false); // The list returned is unsorted. Collections.sort(children); if (children.size() == 0) { // Only possible if some other process cancelled our ticket. logger.warn("getChildren() returned empty list, but we created a ticket."); return acquireLock(zookeeper, lockNode); } boolean lockingTicketExists = children.get(0).equals(LOCKING_TICKET); if (lockingTicketExists) { children.remove(0); } // Where are we in the queue? int positionInQueue = -1; int i = 0; for (String child : children) { if (child.equals(placeInLine)) { positionInQueue = i; break; } i++; } if (positionInQueue < 0) { // Theoretically not possible. throw new RuntimeException("Created node (" + placeInLine + ") not found in getChildren()."); } String placeBeforeUs; if (positionInQueue == 0) { // Lowest number in the queue, go for the lock. if (grabTicket(zookeeper, lockNode, LOCKING_TICKET)) { releaseTicket(zookeeper, lockNode, placeInLine); return LOCKING_TICKET; } else { placeBeforeUs = LOCKING_TICKET; } } else { // We are not in front of the queue, so we keep an eye on the znode right in front of us. When it is // deleted, that means it has reached the front of the queue, acquired the lock, did its business, // and released the lock. placeBeforeUs = children.get(positionInQueue - 1); } final CountDownLatch latch = new CountDownLatch(1); Stat stat = zookeeper.exists(lockNode + "/" + placeBeforeUs, event -> { // If *anything* changes, reevaluate our position in the queue. latch.countDown(); }); // If stat is null, the znode in front of use got deleted during our inspection of the queue. If that happens, // simply reevaluate our position in the queue again. If there *is* a znode in front of us, // watch it for changes: if (stat != null) { logger.debug("Watching place in queue before us ({})", placeBeforeUs); latch.await(); } return waitInLine(zookeeper, lockNode, placeInLine); }
[ "static", "String", "waitInLine", "(", "ZooKeeper", "zookeeper", ",", "String", "lockNode", ",", "String", "placeInLine", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "// Get the list of nodes in the queue, and find out what our position is.", "List", "...
Wait in the queue until the znode in front of us changes. @param zookeeper ZooKeeper connection to use. @param lockNode Path to the znode representing the locking queue. @param placeInLine Name of our current position in the queue. @return Name of the first node in the queue, when we are it.
[ "Wait", "in", "the", "queue", "until", "the", "znode", "in", "front", "of", "us", "changes", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L225-L292
36,917
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.grabTicket
static boolean grabTicket(ZooKeeper zookeeper, String lockNode, String ticket) throws InterruptedException, KeeperException { try { zookeeper.create(lockNode + "/" + ticket, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } catch (KeeperException e) { if (e.code() == KeeperException.Code.NODEEXISTS) { // It is possible that two processes try to grab the exact same ticket at the same time. // This is common for the locking ticket. logger.debug("Failed to claim ticket {}.", ticket); return false; } else { throw e; } } logger.debug("Claimed ticket {}.", ticket); return true; }
java
static boolean grabTicket(ZooKeeper zookeeper, String lockNode, String ticket) throws InterruptedException, KeeperException { try { zookeeper.create(lockNode + "/" + ticket, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } catch (KeeperException e) { if (e.code() == KeeperException.Code.NODEEXISTS) { // It is possible that two processes try to grab the exact same ticket at the same time. // This is common for the locking ticket. logger.debug("Failed to claim ticket {}.", ticket); return false; } else { throw e; } } logger.debug("Claimed ticket {}.", ticket); return true; }
[ "static", "boolean", "grabTicket", "(", "ZooKeeper", "zookeeper", ",", "String", "lockNode", ",", "String", "ticket", ")", "throws", "InterruptedException", ",", "KeeperException", "{", "try", "{", "zookeeper", ".", "create", "(", "lockNode", "+", "\"/\"", "+", ...
Grab a ticket in the queue. @param zookeeper ZooKeeper connection to use. @param lockNode Path to the znode representing the locking queue. @param ticket Name of the ticket to attempt to grab. @return True on success, false if the ticket was already grabbed by another process.
[ "Grab", "a", "ticket", "in", "the", "queue", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L302-L318
36,918
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.claimResource
int claimResource(ZooKeeper zookeeper, String poolNode, int poolSize) throws KeeperException, InterruptedException { logger.debug("Trying to claim a resource."); List<String> claimedResources = zookeeper.getChildren(poolNode, false); if (claimedResources.size() >= poolSize) { logger.debug("No resources available at the moment (pool size: {}), waiting.", poolSize); // No resources available. Wait for a resource to become available. final CountDownLatch latch = new CountDownLatch(1); zookeeper.getChildren(poolNode, event -> latch.countDown()); latch.await(); return claimResource(zookeeper, poolNode, poolSize); } // Try to claim an available resource. for (int i = 0; i < poolSize; i++) { String resourcePath = Integer.toString(i); if (!claimedResources.contains(resourcePath)) { String node; try { logger.debug("Trying to claim seemingly available resource {}.", resourcePath); node = zookeeper.create( poolNode + "/" + resourcePath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL ); } catch (KeeperException e) { if (e.code() == KeeperException.Code.NODEEXISTS) { // Failed to claim this resource for some reason. continue; } else { // Unexpected failure. throw e; } } zookeeper.exists(node, event -> { if (event.getType() == EventType.NodeDeleted) { // Invalidate our claim when the node is deleted by some other process. logger.debug("Resource-claim node unexpectedly deleted ({})", resource); close(true); } }); logger.debug("Successfully claimed resource {}.", resourcePath); return i; } } return claimResource(zookeeper, poolNode, poolSize); }
java
int claimResource(ZooKeeper zookeeper, String poolNode, int poolSize) throws KeeperException, InterruptedException { logger.debug("Trying to claim a resource."); List<String> claimedResources = zookeeper.getChildren(poolNode, false); if (claimedResources.size() >= poolSize) { logger.debug("No resources available at the moment (pool size: {}), waiting.", poolSize); // No resources available. Wait for a resource to become available. final CountDownLatch latch = new CountDownLatch(1); zookeeper.getChildren(poolNode, event -> latch.countDown()); latch.await(); return claimResource(zookeeper, poolNode, poolSize); } // Try to claim an available resource. for (int i = 0; i < poolSize; i++) { String resourcePath = Integer.toString(i); if (!claimedResources.contains(resourcePath)) { String node; try { logger.debug("Trying to claim seemingly available resource {}.", resourcePath); node = zookeeper.create( poolNode + "/" + resourcePath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL ); } catch (KeeperException e) { if (e.code() == KeeperException.Code.NODEEXISTS) { // Failed to claim this resource for some reason. continue; } else { // Unexpected failure. throw e; } } zookeeper.exists(node, event -> { if (event.getType() == EventType.NodeDeleted) { // Invalidate our claim when the node is deleted by some other process. logger.debug("Resource-claim node unexpectedly deleted ({})", resource); close(true); } }); logger.debug("Successfully claimed resource {}.", resourcePath); return i; } } return claimResource(zookeeper, poolNode, poolSize); }
[ "int", "claimResource", "(", "ZooKeeper", "zookeeper", ",", "String", "poolNode", ",", "int", "poolSize", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "logger", ".", "debug", "(", "\"Trying to claim a resource.\"", ")", ";", "List", "<", "St...
Try to claim an available resource from the resource pool. @param zookeeper ZooKeeper connection to use. @param poolNode Path to the znode representing the resource pool. @param poolSize Size of the resource pool. @return The claimed resource.
[ "Try", "to", "claim", "an", "available", "resource", "from", "the", "resource", "pool", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L328-L379
36,919
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.relinquishResource
private void relinquishResource(ZooKeeper zookeeper, String poolNode, int resource) { logger.debug("Relinquishing claimed resource {}.", resource); try { zookeeper.delete(poolNode + "/" + Integer.toString(resource), -1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (KeeperException e) { logger.error("Failed to remove resource claim node {}/{}", poolNode, resource); } }
java
private void relinquishResource(ZooKeeper zookeeper, String poolNode, int resource) { logger.debug("Relinquishing claimed resource {}.", resource); try { zookeeper.delete(poolNode + "/" + Integer.toString(resource), -1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (KeeperException e) { logger.error("Failed to remove resource claim node {}/{}", poolNode, resource); } }
[ "private", "void", "relinquishResource", "(", "ZooKeeper", "zookeeper", ",", "String", "poolNode", ",", "int", "resource", ")", "{", "logger", ".", "debug", "(", "\"Relinquishing claimed resource {}.\"", ",", "resource", ")", ";", "try", "{", "zookeeper", ".", "...
Relinquish a claimed resource. @param zookeeper ZooKeeper connection to use. @param poolNode Path to the znode representing the resource pool. @param resource The resource.
[ "Relinquish", "a", "claimed", "resource", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L388-L397
36,920
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ClusterID.java
ClusterID.get
public static int get(ZooKeeper zookeeper, String znode) throws IOException { try { Stat stat = zookeeper.exists(znode + CLUSTER_ID_NODE, false); if (stat == null) { mkdirp(zookeeper, znode); create(zookeeper, znode + CLUSTER_ID_NODE, String.valueOf(DEFAULT_CLUSTER_ID).getBytes()); } byte[] id = zookeeper.getData(znode + CLUSTER_ID_NODE, false, null); return Integer.valueOf(new String(id)); } catch (KeeperException e) { throw new IOException(String.format("Failed to retrieve the cluster ID from the ZooKeeper quorum. " + "Expected to find it at znode %s.", znode + CLUSTER_ID_NODE), e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } }
java
public static int get(ZooKeeper zookeeper, String znode) throws IOException { try { Stat stat = zookeeper.exists(znode + CLUSTER_ID_NODE, false); if (stat == null) { mkdirp(zookeeper, znode); create(zookeeper, znode + CLUSTER_ID_NODE, String.valueOf(DEFAULT_CLUSTER_ID).getBytes()); } byte[] id = zookeeper.getData(znode + CLUSTER_ID_NODE, false, null); return Integer.valueOf(new String(id)); } catch (KeeperException e) { throw new IOException(String.format("Failed to retrieve the cluster ID from the ZooKeeper quorum. " + "Expected to find it at znode %s.", znode + CLUSTER_ID_NODE), e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } }
[ "public", "static", "int", "get", "(", "ZooKeeper", "zookeeper", ",", "String", "znode", ")", "throws", "IOException", "{", "try", "{", "Stat", "stat", "=", "zookeeper", ".", "exists", "(", "znode", "+", "CLUSTER_ID_NODE", ",", "false", ")", ";", "if", "...
Retrieves the numeric cluster ID from the ZooKeeper quorum. @param zookeeper ZooKeeper instance to work with. @return The cluster ID, if configured in the quorum. @throws IOException Thrown when retrieving the ID fails. @throws NumberFormatException Thrown when the supposed ID found in the quorum could not be parsed as an integer.
[ "Retrieves", "the", "numeric", "cluster", "ID", "from", "the", "ZooKeeper", "quorum", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ClusterID.java#L43-L60
36,921
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ZooKeeperHelper.java
ZooKeeperHelper.pathParts
static List<String> pathParts(String path) { String[] pathParts = path.split("/"); List<String> parts = new ArrayList<>(pathParts.length); String pathSoFar = ""; for (String pathPart : pathParts) { if (!pathPart.equals("")) { pathSoFar += "/" + pathPart; parts.add(pathSoFar); } } return parts; }
java
static List<String> pathParts(String path) { String[] pathParts = path.split("/"); List<String> parts = new ArrayList<>(pathParts.length); String pathSoFar = ""; for (String pathPart : pathParts) { if (!pathPart.equals("")) { pathSoFar += "/" + pathPart; parts.add(pathSoFar); } } return parts; }
[ "static", "List", "<", "String", ">", "pathParts", "(", "String", "path", ")", "{", "String", "[", "]", "pathParts", "=", "path", ".", "split", "(", "\"/\"", ")", ";", "List", "<", "String", ">", "parts", "=", "new", "ArrayList", "<>", "(", "pathPart...
Parse a znode path, and return a list containing the full paths to its constituent directories. @param path Path to parse. @return List of paths.
[ "Parse", "a", "znode", "path", "and", "return", "a", "list", "containing", "the", "full", "paths", "to", "its", "constituent", "directories", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ZooKeeperHelper.java#L106-L117
36,922
LableOrg/java-uniqueid
uniqueid-core/src/main/java/org/lable/oss/uniqueid/LocalUniqueIDGeneratorFactory.java
LocalUniqueIDGeneratorFactory.generatorFor
public synchronized static IDGenerator generatorFor(int generatorId, int clusterId, Mode mode) { assertParameterWithinBounds("generatorId", 0, Blueprint.MAX_GENERATOR_ID, generatorId); assertParameterWithinBounds("clusterId", 0, Blueprint.MAX_CLUSTER_ID, clusterId); String generatorAndCluster = String.format("%d_%d", generatorId, clusterId); if (!instances.containsKey(generatorAndCluster)) { GeneratorIdentityHolder identityHolder = LocalGeneratorIdentity.with(clusterId, generatorId); instances.putIfAbsent(generatorAndCluster, new BaseUniqueIDGenerator(identityHolder, mode)); } return instances.get(generatorAndCluster); }
java
public synchronized static IDGenerator generatorFor(int generatorId, int clusterId, Mode mode) { assertParameterWithinBounds("generatorId", 0, Blueprint.MAX_GENERATOR_ID, generatorId); assertParameterWithinBounds("clusterId", 0, Blueprint.MAX_CLUSTER_ID, clusterId); String generatorAndCluster = String.format("%d_%d", generatorId, clusterId); if (!instances.containsKey(generatorAndCluster)) { GeneratorIdentityHolder identityHolder = LocalGeneratorIdentity.with(clusterId, generatorId); instances.putIfAbsent(generatorAndCluster, new BaseUniqueIDGenerator(identityHolder, mode)); } return instances.get(generatorAndCluster); }
[ "public", "synchronized", "static", "IDGenerator", "generatorFor", "(", "int", "generatorId", ",", "int", "clusterId", ",", "Mode", "mode", ")", "{", "assertParameterWithinBounds", "(", "\"generatorId\"", ",", "0", ",", "Blueprint", ".", "MAX_GENERATOR_ID", ",", "...
Return the UniqueIDGenerator instance for this specific generator-ID, cluster-ID combination. If one was already created, that is returned. @param generatorId Generator ID to use (0 ≤ n ≤ 255). @param clusterId Cluster ID to use (0 ≤ n ≤ 15). @param mode Generator mode. @return A thread-safe UniqueIDGenerator instance.
[ "Return", "the", "UniqueIDGenerator", "instance", "for", "this", "specific", "generator", "-", "ID", "cluster", "-", "ID", "combination", ".", "If", "one", "was", "already", "created", "that", "is", "returned", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-core/src/main/java/org/lable/oss/uniqueid/LocalUniqueIDGeneratorFactory.java#L45-L54
36,923
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/connection/ZooKeeperConnection.java
ZooKeeperConnection.connect
private ZooKeeper connect(String quorumAddresses) throws IOException { final CountDownLatch latch = new CountDownLatch(1); ZooKeeper zookeeper; // Connect to the quorum and wait for the successful connection callback.; zookeeper = new ZooKeeper(quorumAddresses, (int) SECONDS.toMillis(10), watchedEvent -> { if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) { // Signal that the Zookeeper connection is established. latch.countDown(); } }); boolean successfullyConnected = false; try { successfullyConnected = latch.await(11, SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (!successfullyConnected) { throw new IOException(String.format( "Connection to ZooKeeper quorum timed out after %d seconds.", CONNECTION_TIMEOUT)); } return zookeeper; }
java
private ZooKeeper connect(String quorumAddresses) throws IOException { final CountDownLatch latch = new CountDownLatch(1); ZooKeeper zookeeper; // Connect to the quorum and wait for the successful connection callback.; zookeeper = new ZooKeeper(quorumAddresses, (int) SECONDS.toMillis(10), watchedEvent -> { if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) { // Signal that the Zookeeper connection is established. latch.countDown(); } }); boolean successfullyConnected = false; try { successfullyConnected = latch.await(11, SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (!successfullyConnected) { throw new IOException(String.format( "Connection to ZooKeeper quorum timed out after %d seconds.", CONNECTION_TIMEOUT)); } return zookeeper; }
[ "private", "ZooKeeper", "connect", "(", "String", "quorumAddresses", ")", "throws", "IOException", "{", "final", "CountDownLatch", "latch", "=", "new", "CountDownLatch", "(", "1", ")", ";", "ZooKeeper", "zookeeper", ";", "// Connect to the quorum and wait for the succes...
Connect to the ZooKeeper quorum, or timeout if it is unreachable. @throws IOException Thrown when connecting to the ZooKeeper quorum fails.
[ "Connect", "to", "the", "ZooKeeper", "quorum", "or", "timeout", "if", "it", "is", "unreachable", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/connection/ZooKeeperConnection.java#L153-L177
36,924
LableOrg/java-uniqueid
uniqueid-core/src/main/java/org/lable/oss/uniqueid/AutoRefillStack.java
AutoRefillStack.popOne
byte[] popOne() throws GeneratorException { try { return idStack.pop(); } catch (NoSuchElementException e) { // Cached stack is empty, load up a fresh stack. idStack.addAll(generator.batch(batchSize)); return popOne(); } }
java
byte[] popOne() throws GeneratorException { try { return idStack.pop(); } catch (NoSuchElementException e) { // Cached stack is empty, load up a fresh stack. idStack.addAll(generator.batch(batchSize)); return popOne(); } }
[ "byte", "[", "]", "popOne", "(", ")", "throws", "GeneratorException", "{", "try", "{", "return", "idStack", ".", "pop", "(", ")", ";", "}", "catch", "(", "NoSuchElementException", "e", ")", "{", "// Cached stack is empty, load up a fresh stack.", "idStack", ".",...
Grab a single ID from the stack. If the stack is empty, load up a new batch from the wrapped generator. @return A single ID.
[ "Grab", "a", "single", "ID", "from", "the", "stack", ".", "If", "the", "stack", "is", "empty", "load", "up", "a", "new", "batch", "from", "the", "wrapped", "generator", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-core/src/main/java/org/lable/oss/uniqueid/AutoRefillStack.java#L101-L109
36,925
LableOrg/java-uniqueid
uniqueid-core/src/main/java/org/lable/oss/uniqueid/bytes/IDBuilder.java
IDBuilder.build
public static byte[] build(Blueprint blueprint) { // First 42 bits are the timestamp. // [0] TTTTTTTT [1] TTTTTTTT [2] TTTTTTTT [3] TTTTTTTT [4] TTTTTTTT [5] TT...... ByteBuffer bb = ByteBuffer.allocate(8); switch (blueprint.getMode()) { case SPREAD: long reverseTimestamp = Long.reverse(blueprint.getTimestamp()); bb.putLong(reverseTimestamp); break; case TIME_SEQUENTIAL: long timestamp = blueprint.getTimestamp(); bb.putLong(timestamp << 22); break; } byte[] tsBytes = bb.array(); // Last 6 bits of byte 6 are for the sequence counter. The first two bits are from the timestamp. // [5] TTSSSSSS int or = tsBytes[5] | (byte) blueprint.getSequence(); tsBytes[5] = (byte) or; // Last two bytes. The mode flag, generator ID, and cluster ID. // [6] ...MGGGG [7] GGGGCCCC int flagGeneratorCluster = blueprint.getGeneratorId() << 4; flagGeneratorCluster += blueprint.getClusterId(); flagGeneratorCluster += blueprint.getMode().getModeMask() << 12; tsBytes[7] = (byte) flagGeneratorCluster; flagGeneratorCluster >>>= 8; tsBytes[6] = (byte) flagGeneratorCluster; return tsBytes; }
java
public static byte[] build(Blueprint blueprint) { // First 42 bits are the timestamp. // [0] TTTTTTTT [1] TTTTTTTT [2] TTTTTTTT [3] TTTTTTTT [4] TTTTTTTT [5] TT...... ByteBuffer bb = ByteBuffer.allocate(8); switch (blueprint.getMode()) { case SPREAD: long reverseTimestamp = Long.reverse(blueprint.getTimestamp()); bb.putLong(reverseTimestamp); break; case TIME_SEQUENTIAL: long timestamp = blueprint.getTimestamp(); bb.putLong(timestamp << 22); break; } byte[] tsBytes = bb.array(); // Last 6 bits of byte 6 are for the sequence counter. The first two bits are from the timestamp. // [5] TTSSSSSS int or = tsBytes[5] | (byte) blueprint.getSequence(); tsBytes[5] = (byte) or; // Last two bytes. The mode flag, generator ID, and cluster ID. // [6] ...MGGGG [7] GGGGCCCC int flagGeneratorCluster = blueprint.getGeneratorId() << 4; flagGeneratorCluster += blueprint.getClusterId(); flagGeneratorCluster += blueprint.getMode().getModeMask() << 12; tsBytes[7] = (byte) flagGeneratorCluster; flagGeneratorCluster >>>= 8; tsBytes[6] = (byte) flagGeneratorCluster; return tsBytes; }
[ "public", "static", "byte", "[", "]", "build", "(", "Blueprint", "blueprint", ")", "{", "// First 42 bits are the timestamp.", "// [0] TTTTTTTT [1] TTTTTTTT [2] TTTTTTTT [3] TTTTTTTT [4] TTTTTTTT [5] TT......", "ByteBuffer", "bb", "=", "ByteBuffer", ".", "allocate", "(", "8",...
Perform all the byte mangling needed to create the eight byte ID. @param blueprint Blueprint containing all needed data to work with. @return The 8-byte ID.
[ "Perform", "all", "the", "byte", "mangling", "needed", "to", "create", "the", "eight", "byte", "ID", "." ]
554e30b2277765f365e7c7f598108de0ab5744f4
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-core/src/main/java/org/lable/oss/uniqueid/bytes/IDBuilder.java#L48-L80
36,926
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/BindingInstaller.java
BindingInstaller.ensureAccessible
private void ensureAccessible(Key<?> key, GinjectorBindings parent, GinjectorBindings child) { // Parent will be null if it is was an optional dependency and it couldn't be created. if (parent != null && !child.equals(parent) && !child.isBound(key)) { PrettyPrinter.log(logger, TreeLogger.DEBUG, "In %s: inheriting binding for %s from the parent %s", child, key, parent); Context context = Context.format("Inheriting %s from parent", key); // We don't strictly need all the extra checks in addBinding, but it can't hurt. We know, for // example, that there will not be any unresolved bindings for this key. child.addBinding(key, bindingFactory.getParentBinding(key, parent, context)); } }
java
private void ensureAccessible(Key<?> key, GinjectorBindings parent, GinjectorBindings child) { // Parent will be null if it is was an optional dependency and it couldn't be created. if (parent != null && !child.equals(parent) && !child.isBound(key)) { PrettyPrinter.log(logger, TreeLogger.DEBUG, "In %s: inheriting binding for %s from the parent %s", child, key, parent); Context context = Context.format("Inheriting %s from parent", key); // We don't strictly need all the extra checks in addBinding, but it can't hurt. We know, for // example, that there will not be any unresolved bindings for this key. child.addBinding(key, bindingFactory.getParentBinding(key, parent, context)); } }
[ "private", "void", "ensureAccessible", "(", "Key", "<", "?", ">", "key", ",", "GinjectorBindings", "parent", ",", "GinjectorBindings", "child", ")", "{", "// Parent will be null if it is was an optional dependency and it couldn't be created.", "if", "(", "parent", "!=", "...
Ensure that the binding for key which exists in the parent Ginjector is also available to the child Ginjector.
[ "Ensure", "that", "the", "binding", "for", "key", "which", "exists", "in", "the", "parent", "Ginjector", "is", "also", "available", "to", "the", "child", "Ginjector", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/BindingInstaller.java#L116-L127
36,927
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/GuiceUtil.java
GuiceUtil.getKey
public Key<?> getKey(FieldLiteral<?> field) { return getKey(field.getFieldType().getType(), field.getBindingAnnotation()); }
java
public Key<?> getKey(FieldLiteral<?> field) { return getKey(field.getFieldType().getType(), field.getBindingAnnotation()); }
[ "public", "Key", "<", "?", ">", "getKey", "(", "FieldLiteral", "<", "?", ">", "field", ")", "{", "return", "getKey", "(", "field", ".", "getFieldType", "(", ")", ".", "getType", "(", ")", ",", "field", ".", "getBindingAnnotation", "(", ")", ")", ";",...
Returns a key based on the passed field, taking any binding annotations into account. @param field field for which to retrieve the key @return key for passed field
[ "Returns", "a", "key", "based", "on", "the", "passed", "field", "taking", "any", "binding", "annotations", "into", "account", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/GuiceUtil.java#L76-L78
36,928
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/GuiceUtil.java
GuiceUtil.getKey
private Key<?> getKey(Type type, Annotation bindingAnnotation) throws ProvisionException { if (bindingAnnotation == null) { return Key.get(type); } else { return Key.get(type, bindingAnnotation); } }
java
private Key<?> getKey(Type type, Annotation bindingAnnotation) throws ProvisionException { if (bindingAnnotation == null) { return Key.get(type); } else { return Key.get(type, bindingAnnotation); } }
[ "private", "Key", "<", "?", ">", "getKey", "(", "Type", "type", ",", "Annotation", "bindingAnnotation", ")", "throws", "ProvisionException", "{", "if", "(", "bindingAnnotation", "==", "null", ")", "{", "return", "Key", ".", "get", "(", "type", ")", ";", ...
Gets the Guice binding key for a given Java type with optional annotations. @param type Java type to convert in to a key @param bindingAnnotation binding annotation for this key @return Guice Key instance for this type/annotations @throws ProvisionException in case of any failure
[ "Gets", "the", "Guice", "binding", "key", "for", "a", "given", "Java", "type", "with", "optional", "annotations", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/GuiceUtil.java#L89-L95
36,929
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/GuiceUtil.java
GuiceUtil.getMemberInjectionDependencies
public Collection<Dependency> getMemberInjectionDependencies( Key<?> typeKey, TypeLiteral<?> type) { Set<Dependency> required = new LinkedHashSet<Dependency>(); for (MethodLiteral<?, Method> method : memberCollector.getMethods(type)) { required.addAll(getDependencies(typeKey, method)); } for (FieldLiteral<?> field : memberCollector.getFields(type)) { Key<?> key = getKey(field); required.add(new Dependency(typeKey, key, isOptional(field), false, "member injection of " + field)); } return required; }
java
public Collection<Dependency> getMemberInjectionDependencies( Key<?> typeKey, TypeLiteral<?> type) { Set<Dependency> required = new LinkedHashSet<Dependency>(); for (MethodLiteral<?, Method> method : memberCollector.getMethods(type)) { required.addAll(getDependencies(typeKey, method)); } for (FieldLiteral<?> field : memberCollector.getFields(type)) { Key<?> key = getKey(field); required.add(new Dependency(typeKey, key, isOptional(field), false, "member injection of " + field)); } return required; }
[ "public", "Collection", "<", "Dependency", ">", "getMemberInjectionDependencies", "(", "Key", "<", "?", ">", "typeKey", ",", "TypeLiteral", "<", "?", ">", "type", ")", "{", "Set", "<", "Dependency", ">", "required", "=", "new", "LinkedHashSet", "<", "Depende...
Collects and returns all keys required to member-inject the given class. @param typeKey key causing member injection @param type class for which required keys are calculated @return keys required to inject given class
[ "Collects", "and", "returns", "all", "keys", "required", "to", "member", "-", "inject", "the", "given", "class", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/GuiceUtil.java#L134-L147
36,930
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/GuiceUtil.java
GuiceUtil.getDependencies
public Collection<Dependency> getDependencies(Key<?> typeKey, MethodLiteral<?, ?> method) { String context; if (method.isConstructor()) { context = "@Inject constructor of " + method.getDeclaringType(); } else if (typeKey == Dependency.GINJECTOR) { context = "Member injector " + method; } else { context = "Member injection via " + method; } Set<Dependency> required = new LinkedHashSet<Dependency>(); for (Key<?> key : method.getParameterKeys()) { required.add(new Dependency(typeKey, key, isOptional(method), false, context)); } return required; }
java
public Collection<Dependency> getDependencies(Key<?> typeKey, MethodLiteral<?, ?> method) { String context; if (method.isConstructor()) { context = "@Inject constructor of " + method.getDeclaringType(); } else if (typeKey == Dependency.GINJECTOR) { context = "Member injector " + method; } else { context = "Member injection via " + method; } Set<Dependency> required = new LinkedHashSet<Dependency>(); for (Key<?> key : method.getParameterKeys()) { required.add(new Dependency(typeKey, key, isOptional(method), false, context)); } return required; }
[ "public", "Collection", "<", "Dependency", ">", "getDependencies", "(", "Key", "<", "?", ">", "typeKey", ",", "MethodLiteral", "<", "?", ",", "?", ">", "method", ")", "{", "String", "context", ";", "if", "(", "method", ".", "isConstructor", "(", ")", "...
Collects and returns all keys required to inject the given method. @param typeKey the key that depends on injecting the arguments of method @param method method for which required keys are calculated @return required keys
[ "Collects", "and", "returns", "all", "keys", "required", "to", "inject", "the", "given", "method", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/GuiceUtil.java#L156-L172
36,931
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/reflect/FieldLiteral.java
FieldLiteral.get
public static <T> FieldLiteral<T> get(Field field, TypeLiteral<T> declaringType) { Preconditions.checkArgument( field.getDeclaringClass().equals(declaringType.getRawType()), "declaringType (%s) must be the type literal where field was declared (%s)!", declaringType, field.getDeclaringClass()); return new FieldLiteral<T>(field, declaringType); }
java
public static <T> FieldLiteral<T> get(Field field, TypeLiteral<T> declaringType) { Preconditions.checkArgument( field.getDeclaringClass().equals(declaringType.getRawType()), "declaringType (%s) must be the type literal where field was declared (%s)!", declaringType, field.getDeclaringClass()); return new FieldLiteral<T>(field, declaringType); }
[ "public", "static", "<", "T", ">", "FieldLiteral", "<", "T", ">", "get", "(", "Field", "field", ",", "TypeLiteral", "<", "T", ">", "declaringType", ")", "{", "Preconditions", ".", "checkArgument", "(", "field", ".", "getDeclaringClass", "(", ")", ".", "e...
Returns a new field literal based on the passed field and its declaring type. @param field field for which the literal is created @param declaringType the field's declaring type @return new field literal
[ "Returns", "a", "new", "field", "literal", "based", "on", "the", "passed", "field", "and", "its", "declaring", "type", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/reflect/FieldLiteral.java#L41-L47
36,932
gwtplus/google-gin
src/it/higher-lower/src/main/java/com/google/gwt/gin/higherlower/client/DefaultHigherLowerGame.java
DefaultHigherLowerGame.displayNextCard
public PlayerGuessResult displayNextCard(RelationshipToPreviousCard guess) { Card card = deck.turnCard(); grid.nextCard(card); cardsTurnedPlusOne++; RelationshipToPreviousCard actualRelationshipToPrevious = getRelationshipToPreviousCard(card); previous = card; if (actualRelationshipToPrevious == null) { return null; } return actualRelationshipToPrevious.equals(guess) ? PlayerGuessResult.RIGHT : PlayerGuessResult.WRONG; }
java
public PlayerGuessResult displayNextCard(RelationshipToPreviousCard guess) { Card card = deck.turnCard(); grid.nextCard(card); cardsTurnedPlusOne++; RelationshipToPreviousCard actualRelationshipToPrevious = getRelationshipToPreviousCard(card); previous = card; if (actualRelationshipToPrevious == null) { return null; } return actualRelationshipToPrevious.equals(guess) ? PlayerGuessResult.RIGHT : PlayerGuessResult.WRONG; }
[ "public", "PlayerGuessResult", "displayNextCard", "(", "RelationshipToPreviousCard", "guess", ")", "{", "Card", "card", "=", "deck", ".", "turnCard", "(", ")", ";", "grid", ".", "nextCard", "(", "card", ")", ";", "cardsTurnedPlusOne", "++", ";", "RelationshipToP...
Turn the next card. @param guess the player's guess @return whether the player was right or wrong
[ "Turn", "the", "next", "card", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/it/higher-lower/src/main/java/com/google/gwt/gin/higherlower/client/DefaultHigherLowerGame.java#L29-L41
36,933
gwtplus/google-gin
src/main/java/com/google/gwt/inject/client/PrivateGinModule.java
PrivateGinModule.bind
protected final <T> GinAnnotatedBindingBuilder<T> bind(Class<T> clazz) { return binder.bind(clazz); }
java
protected final <T> GinAnnotatedBindingBuilder<T> bind(Class<T> clazz) { return binder.bind(clazz); }
[ "protected", "final", "<", "T", ">", "GinAnnotatedBindingBuilder", "<", "T", ">", "bind", "(", "Class", "<", "T", ">", "clazz", ")", "{", "return", "binder", ".", "bind", "(", "clazz", ")", ";", "}" ]
Everything below is copied from AbstractGinModule
[ "Everything", "below", "is", "copied", "from", "AbstractGinModule" ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/client/PrivateGinModule.java#L87-L89
36,934
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/binding/BindConstantBinding.java
BindConstantBinding.isConstantKey
public static boolean isConstantKey(Key<?> key) { Type type = key.getTypeLiteral().getType(); if (!(type instanceof Class)) { return false; } Class clazz = (Class) type; return clazz == String.class || clazz == Class.class || clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz) || clazz.isEnum(); }
java
public static boolean isConstantKey(Key<?> key) { Type type = key.getTypeLiteral().getType(); if (!(type instanceof Class)) { return false; } Class clazz = (Class) type; return clazz == String.class || clazz == Class.class || clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz) || clazz.isEnum(); }
[ "public", "static", "boolean", "isConstantKey", "(", "Key", "<", "?", ">", "key", ")", "{", "Type", "type", "=", "key", ".", "getTypeLiteral", "(", ")", ".", "getType", "(", ")", ";", "if", "(", "!", "(", "type", "instanceof", "Class", ")", ")", "{...
Returns true if the provided key is a valid constant key, i.e. if a constant binding can be legally created for it. @param key key to check @return true if constant key
[ "Returns", "true", "if", "the", "provided", "key", "is", "a", "valid", "constant", "key", "i", ".", "e", ".", "if", "a", "constant", "binding", "can", "be", "legally", "created", "for", "it", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/binding/BindConstantBinding.java#L50-L61
36,935
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/PrettyPrinter.java
PrettyPrinter.log
public static void log(TreeLogger logger, TreeLogger.Type type, String formatString, Object... args) { if (logger.isLoggable(type)) { logger.log(type, format(formatString, args)); } }
java
public static void log(TreeLogger logger, TreeLogger.Type type, String formatString, Object... args) { if (logger.isLoggable(type)) { logger.log(type, format(formatString, args)); } }
[ "public", "static", "void", "log", "(", "TreeLogger", "logger", ",", "TreeLogger", ".", "Type", "type", ",", "String", "formatString", ",", "Object", "...", "args", ")", "{", "if", "(", "logger", ".", "isLoggable", "(", "type", ")", ")", "{", "logger", ...
Log a pretty-printed message if the given log level is active. The message is only formatted if it will be logged.
[ "Log", "a", "pretty", "-", "printed", "message", "if", "the", "given", "log", "level", "is", "active", ".", "The", "message", "is", "only", "formatted", "if", "it", "will", "be", "logged", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/PrettyPrinter.java#L54-L59
36,936
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/PrettyPrinter.java
PrettyPrinter.formatObject
private static Object formatObject(Object object) { if (object instanceof Class) { return formatArg((Class<?>) object); } else if (object instanceof Key) { return formatArg((Key<?>) object); } else if (object instanceof List) { List<?> list = (List<?>) object; // Empirically check if this is a List<Dependency>. boolean allDependencies = true; for (Object entry : list) { if (!(entry instanceof Dependency)) { allDependencies = false; break; } } if (allDependencies) { return formatArg((List<Dependency>) list); } else { return object; } } else { return object; } }
java
private static Object formatObject(Object object) { if (object instanceof Class) { return formatArg((Class<?>) object); } else if (object instanceof Key) { return formatArg((Key<?>) object); } else if (object instanceof List) { List<?> list = (List<?>) object; // Empirically check if this is a List<Dependency>. boolean allDependencies = true; for (Object entry : list) { if (!(entry instanceof Dependency)) { allDependencies = false; break; } } if (allDependencies) { return formatArg((List<Dependency>) list); } else { return object; } } else { return object; } }
[ "private", "static", "Object", "formatObject", "(", "Object", "object", ")", "{", "if", "(", "object", "instanceof", "Class", ")", "{", "return", "formatArg", "(", "(", "Class", "<", "?", ">", ")", "object", ")", ";", "}", "else", "if", "(", "object", ...
Pretty-print a single object.
[ "Pretty", "-", "print", "a", "single", "object", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/PrettyPrinter.java#L81-L105
36,937
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/binding/FactoryBinding.java
FactoryBinding.extractConstructorParameters
private String[] extractConstructorParameters(Key<?> factoryKey, TypeLiteral<?> implementation, Constructor constructor, List<Key<?>> methodParams, Errors errors, Set<Dependency> dependencyCollector) throws ErrorsException { // Get parameters with annotations. List<TypeLiteral<?>> ctorParams = implementation.getParameterTypes(constructor); Annotation[][] ctorParamAnnotations = constructor.getParameterAnnotations(); int p = 0; String[] parameterNames = new String[ctorParams.size()]; Set<Key<?>> keySet = new LinkedHashSet<Key<?>>(); for (TypeLiteral<?> ctorParam : ctorParams) { Key<?> ctorParamKey = getKey(ctorParam, constructor, ctorParamAnnotations[p], errors); if (ctorParamKey.getAnnotationType() == Assisted.class) { if (!keySet.add(ctorParamKey)) { errors.addMessage(PrettyPrinter.format( "%s has more than one parameter of type %s annotated with @Assisted(\"%s\"). " + "Please specify a unique value with the annotation to avoid confusion.", implementation, ctorParamKey.getTypeLiteral().getType(), ((Assisted) ctorParamKey.getAnnotation()).value())); } int location = methodParams.indexOf(ctorParamKey); // This should never happen since the constructor was already checked // in #[inject]constructorHasMatchingParams(..). Preconditions.checkState(location != -1); parameterNames[p] = ReflectUtil.formatParameterName(location); } else { dependencyCollector.add(new Dependency(factoryKey, ctorParamKey, false, true, constructor.toString())); } p++; } return parameterNames; }
java
private String[] extractConstructorParameters(Key<?> factoryKey, TypeLiteral<?> implementation, Constructor constructor, List<Key<?>> methodParams, Errors errors, Set<Dependency> dependencyCollector) throws ErrorsException { // Get parameters with annotations. List<TypeLiteral<?>> ctorParams = implementation.getParameterTypes(constructor); Annotation[][] ctorParamAnnotations = constructor.getParameterAnnotations(); int p = 0; String[] parameterNames = new String[ctorParams.size()]; Set<Key<?>> keySet = new LinkedHashSet<Key<?>>(); for (TypeLiteral<?> ctorParam : ctorParams) { Key<?> ctorParamKey = getKey(ctorParam, constructor, ctorParamAnnotations[p], errors); if (ctorParamKey.getAnnotationType() == Assisted.class) { if (!keySet.add(ctorParamKey)) { errors.addMessage(PrettyPrinter.format( "%s has more than one parameter of type %s annotated with @Assisted(\"%s\"). " + "Please specify a unique value with the annotation to avoid confusion.", implementation, ctorParamKey.getTypeLiteral().getType(), ((Assisted) ctorParamKey.getAnnotation()).value())); } int location = methodParams.indexOf(ctorParamKey); // This should never happen since the constructor was already checked // in #[inject]constructorHasMatchingParams(..). Preconditions.checkState(location != -1); parameterNames[p] = ReflectUtil.formatParameterName(location); } else { dependencyCollector.add(new Dependency(factoryKey, ctorParamKey, false, true, constructor.toString())); } p++; } return parameterNames; }
[ "private", "String", "[", "]", "extractConstructorParameters", "(", "Key", "<", "?", ">", "factoryKey", ",", "TypeLiteral", "<", "?", ">", "implementation", ",", "Constructor", "constructor", ",", "List", "<", "Key", "<", "?", ">", ">", "methodParams", ",", ...
Matches constructor parameters to method parameters for injection and records remaining parameters as required keys.
[ "Matches", "constructor", "parameters", "to", "method", "parameters", "for", "injection", "and", "records", "remaining", "parameters", "as", "required", "keys", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/binding/FactoryBinding.java#L264-L303
36,938
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/UnresolvedBindingValidator.java
UnresolvedBindingValidator.pruneInvalidOptional
public void pruneInvalidOptional(DependencyExplorerOutput output, InvalidKeys invalidKeys) { DependencyGraph.GraphPruner prunedGraph = new DependencyGraph.GraphPruner(output.getGraph()); for (Key<?> key : invalidKeys.getInvalidOptionalKeys()) { prunedGraph.remove(key); output.removeBinding(key); } output.setGraph(prunedGraph.update()); }
java
public void pruneInvalidOptional(DependencyExplorerOutput output, InvalidKeys invalidKeys) { DependencyGraph.GraphPruner prunedGraph = new DependencyGraph.GraphPruner(output.getGraph()); for (Key<?> key : invalidKeys.getInvalidOptionalKeys()) { prunedGraph.remove(key); output.removeBinding(key); } output.setGraph(prunedGraph.update()); }
[ "public", "void", "pruneInvalidOptional", "(", "DependencyExplorerOutput", "output", ",", "InvalidKeys", "invalidKeys", ")", "{", "DependencyGraph", ".", "GraphPruner", "prunedGraph", "=", "new", "DependencyGraph", ".", "GraphPruner", "(", "output", ".", "getGraph", "...
Prune all of the invalid optional keys from the graph. After this method, all of the keys remaining in the graph are resolvable.
[ "Prune", "all", "of", "the", "invalid", "optional", "keys", "from", "the", "graph", ".", "After", "this", "method", "all", "of", "the", "keys", "remaining", "in", "the", "graph", "are", "resolvable", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/UnresolvedBindingValidator.java#L110-L117
36,939
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/UnresolvedBindingValidator.java
UnresolvedBindingValidator.getAllInvalidKeys
private Map<Key<?>, String> getAllInvalidKeys(DependencyExplorerOutput output) { Map<Key<?>, String> invalidKeys = new LinkedHashMap<Key<?>, String>(); // Look for errors in the nodes, and either report the error (if its required) or remove the // node (if its optional). for (Entry<Key<?>, String> error : output.getBindingErrors()) { invalidKeys.put(error.getKey(), "Unable to create or inherit binding: " + error.getValue()); } GinjectorBindings origin = output.getGraph().getOrigin(); for (Key<?> key : output.getImplicitlyBoundKeys()) { if (origin.isBoundLocallyInChild(key)) { GinjectorBindings child = origin.getChildWhichBindsLocally(key); Binding childBinding = child.getBinding(key); PrettyPrinter.log(logger, TreeLogger.DEBUG, "Marking the key %s as bound in the ginjector %s (implicitly), and in the child" + " %s (%s)", key, origin, child, childBinding.getContext()); // TODO(schmitt): Determine path to binding in child ginjector (requires // different DependencyExplorerOutput). invalidKeys.put(key, PrettyPrinter.format("Already bound in child Ginjector %s. Consider exposing it?", child)); } } return invalidKeys; }
java
private Map<Key<?>, String> getAllInvalidKeys(DependencyExplorerOutput output) { Map<Key<?>, String> invalidKeys = new LinkedHashMap<Key<?>, String>(); // Look for errors in the nodes, and either report the error (if its required) or remove the // node (if its optional). for (Entry<Key<?>, String> error : output.getBindingErrors()) { invalidKeys.put(error.getKey(), "Unable to create or inherit binding: " + error.getValue()); } GinjectorBindings origin = output.getGraph().getOrigin(); for (Key<?> key : output.getImplicitlyBoundKeys()) { if (origin.isBoundLocallyInChild(key)) { GinjectorBindings child = origin.getChildWhichBindsLocally(key); Binding childBinding = child.getBinding(key); PrettyPrinter.log(logger, TreeLogger.DEBUG, "Marking the key %s as bound in the ginjector %s (implicitly), and in the child" + " %s (%s)", key, origin, child, childBinding.getContext()); // TODO(schmitt): Determine path to binding in child ginjector (requires // different DependencyExplorerOutput). invalidKeys.put(key, PrettyPrinter.format("Already bound in child Ginjector %s. Consider exposing it?", child)); } } return invalidKeys; }
[ "private", "Map", "<", "Key", "<", "?", ">", ",", "String", ">", "getAllInvalidKeys", "(", "DependencyExplorerOutput", "output", ")", "{", "Map", "<", "Key", "<", "?", ">", ",", "String", ">", "invalidKeys", "=", "new", "LinkedHashMap", "<", "Key", "<", ...
Returns a map from keys that are invalid to errors explaining why each key is invalid.
[ "Returns", "a", "map", "from", "keys", "that", "are", "invalid", "to", "errors", "explaining", "why", "each", "key", "is", "invalid", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/UnresolvedBindingValidator.java#L122-L151
36,940
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/UnresolvedBindingValidator.java
UnresolvedBindingValidator.getKeysToRemove
private Set<Key<?>> getKeysToRemove(DependencyGraph graph, Collection<Key<?>> discovered) { Set<Key<?>> toRemove = new LinkedHashSet<Key<?>>(); while (!discovered.isEmpty()) { toRemove.addAll(discovered); discovered = getRequiredSourcesTargeting(graph, discovered); discovered.removeAll(toRemove); } return toRemove; }
java
private Set<Key<?>> getKeysToRemove(DependencyGraph graph, Collection<Key<?>> discovered) { Set<Key<?>> toRemove = new LinkedHashSet<Key<?>>(); while (!discovered.isEmpty()) { toRemove.addAll(discovered); discovered = getRequiredSourcesTargeting(graph, discovered); discovered.removeAll(toRemove); } return toRemove; }
[ "private", "Set", "<", "Key", "<", "?", ">", ">", "getKeysToRemove", "(", "DependencyGraph", "graph", ",", "Collection", "<", "Key", "<", "?", ">", ">", "discovered", ")", "{", "Set", "<", "Key", "<", "?", ">", ">", "toRemove", "=", "new", "LinkedHas...
Given the set of optional keys that had problems, compute the set of all optional keys that should be removed. This may include additional keys, for instance if an optional key requires an invalid key, than the optional key should also be removed. <p>This will only add optional keys to {@code toRemove}. Recall that a key is required iff there exists a path to it that passes through only required edges. If key Y is optional, and there is a required edge from X -> Y, then X must also be optional. If X were required, by our definition Y would also be required.
[ "Given", "the", "set", "of", "optional", "keys", "that", "had", "problems", "compute", "the", "set", "of", "all", "optional", "keys", "that", "should", "be", "removed", ".", "This", "may", "include", "additional", "keys", "for", "instance", "if", "an", "op...
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/UnresolvedBindingValidator.java#L187-L195
36,941
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/UnresolvedBindingValidator.java
UnresolvedBindingValidator.getRequiredSourcesTargeting
private Collection<Key<?>> getRequiredSourcesTargeting( DependencyGraph graph, Iterable<Key<?>> targets) { Collection<Key<?>> requiredSources = new LinkedHashSet<Key<?>>(); for (Key<?> target : targets) { for (Dependency edge : graph.getDependenciesTargeting(target)) { if (!edge.isOptional()) { PrettyPrinter.log(logger, TreeLogger.DEBUG, "Removing the key %s because of %s", edge.getSource(), edge); requiredSources.add(edge.getSource()); } } } return requiredSources; }
java
private Collection<Key<?>> getRequiredSourcesTargeting( DependencyGraph graph, Iterable<Key<?>> targets) { Collection<Key<?>> requiredSources = new LinkedHashSet<Key<?>>(); for (Key<?> target : targets) { for (Dependency edge : graph.getDependenciesTargeting(target)) { if (!edge.isOptional()) { PrettyPrinter.log(logger, TreeLogger.DEBUG, "Removing the key %s because of %s", edge.getSource(), edge); requiredSources.add(edge.getSource()); } } } return requiredSources; }
[ "private", "Collection", "<", "Key", "<", "?", ">", ">", "getRequiredSourcesTargeting", "(", "DependencyGraph", "graph", ",", "Iterable", "<", "Key", "<", "?", ">", ">", "targets", ")", "{", "Collection", "<", "Key", "<", "?", ">", ">", "requiredSources", ...
Returns all of the source keys that have a required dependency on any key in the target set.
[ "Returns", "all", "of", "the", "source", "keys", "that", "have", "a", "required", "dependency", "on", "any", "key", "in", "the", "target", "set", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/UnresolvedBindingValidator.java#L200-L213
36,942
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/GuiceBindingVisitor.java
GuiceBindingVisitor.visitScope
public Void visitScope(Scope scope) { messages.add(new Message(PrettyPrinter.format("Explicit scope unsupported: key=%s scope=%s", targetKey, scope))); return null; }
java
public Void visitScope(Scope scope) { messages.add(new Message(PrettyPrinter.format("Explicit scope unsupported: key=%s scope=%s", targetKey, scope))); return null; }
[ "public", "Void", "visitScope", "(", "Scope", "scope", ")", "{", "messages", ".", "add", "(", "new", "Message", "(", "PrettyPrinter", ".", "format", "(", "\"Explicit scope unsupported: key=%s scope=%s\"", ",", "targetKey", ",", "scope", ")", ")", ")", ";", "re...
strange to be using the Guice Scope instead of javax.inject.Scope
[ "strange", "to", "be", "using", "the", "Guice", "Scope", "instead", "of", "javax", ".", "inject", ".", "Scope" ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/GuiceBindingVisitor.java#L140-L144
36,943
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java
ReflectUtil.getUserPackageName
public static String getUserPackageName(TypeLiteral<?> typeLiteral) { Map<String, Class<?>> packageNames = new LinkedHashMap<String, Class<?>>(); getTypePackageNames(typeLiteral.getType(), packageNames); if (packageNames.size() == 0) { // All type names are public, so typeLiteral is visible from any package. // Arbitrarily put it in the package declaring the top-level class. return typeLiteral.getRawType().getPackage().getName(); } else if (packageNames.size() == 1) { // The type contains names that are private to exactly one package; it // must be referenced from that package. return packageNames.keySet().iterator().next(); } else { // The type literal contains types that are private to two or more // different packages. This can happen if a class uses a type that is // protected in its parent, and its parent is from another package. For // instance: // // package pkg1: // public class Parent { // protected static class ForSubclasses { // } // } // // Here the type ForSubclasses is accessible to anything in the package // "pkg1", but it can't be used in another package: // // package pkg2: // class Foo<T> { // } // // class Child extends Parent { // @Inject Child(Foo<ForSubclasses>) {} // } // // There's no package in which we can place code that can create // Foo<ForSubclasses>, even though the user was able to write that type, // because we would have to subclass Parent to do so. (theoretically we // could write static helper methods inside a subclass, but that seems // like too much trouble to support this sort of weirdness) StringBuilder packageNamesListBuilder = new StringBuilder(); for (Class<?> entry : packageNames.values()) { packageNamesListBuilder.append(entry.getCanonicalName()).append("\n"); } throw new IllegalArgumentException(PrettyPrinter.format( "Unable to inject an instance of %s because it references protected classes" + " from multiple packages:\n%s", typeLiteral, packageNamesListBuilder)); } }
java
public static String getUserPackageName(TypeLiteral<?> typeLiteral) { Map<String, Class<?>> packageNames = new LinkedHashMap<String, Class<?>>(); getTypePackageNames(typeLiteral.getType(), packageNames); if (packageNames.size() == 0) { // All type names are public, so typeLiteral is visible from any package. // Arbitrarily put it in the package declaring the top-level class. return typeLiteral.getRawType().getPackage().getName(); } else if (packageNames.size() == 1) { // The type contains names that are private to exactly one package; it // must be referenced from that package. return packageNames.keySet().iterator().next(); } else { // The type literal contains types that are private to two or more // different packages. This can happen if a class uses a type that is // protected in its parent, and its parent is from another package. For // instance: // // package pkg1: // public class Parent { // protected static class ForSubclasses { // } // } // // Here the type ForSubclasses is accessible to anything in the package // "pkg1", but it can't be used in another package: // // package pkg2: // class Foo<T> { // } // // class Child extends Parent { // @Inject Child(Foo<ForSubclasses>) {} // } // // There's no package in which we can place code that can create // Foo<ForSubclasses>, even though the user was able to write that type, // because we would have to subclass Parent to do so. (theoretically we // could write static helper methods inside a subclass, but that seems // like too much trouble to support this sort of weirdness) StringBuilder packageNamesListBuilder = new StringBuilder(); for (Class<?> entry : packageNames.values()) { packageNamesListBuilder.append(entry.getCanonicalName()).append("\n"); } throw new IllegalArgumentException(PrettyPrinter.format( "Unable to inject an instance of %s because it references protected classes" + " from multiple packages:\n%s", typeLiteral, packageNamesListBuilder)); } }
[ "public", "static", "String", "getUserPackageName", "(", "TypeLiteral", "<", "?", ">", "typeLiteral", ")", "{", "Map", "<", "String", ",", "Class", "<", "?", ">", ">", "packageNames", "=", "new", "LinkedHashMap", "<", "String", ",", "Class", "<", "?", ">...
Return the name of the package from which the given type can be used. <p>Returns a package from which all the type names contained in the given type literal are visible. Throws {@link IllegalArgumentException} if there is no such package. If there are multiple such packages, then the type name can be used from any package; the package containing the outermost class is used arbitrarily. <p>This method is intentionally not overloaded on Class, because it's normally an error to use a raw Class token to determine the package in which to manipulate a type.
[ "Return", "the", "name", "of", "the", "package", "from", "which", "the", "given", "type", "can", "be", "used", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java#L150-L202
36,944
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java
ReflectUtil.getClassPackageNames
private static void getClassPackageNames(Class<?> clazz, Map<String, Class<?>> packageNames) { if (isPrivate(clazz)) { throw new IllegalArgumentException(PrettyPrinter.format( "Unable to inject an instance of %s because it is a private class.", clazz)); } else if (!isPublic(clazz)) { packageNames.put(clazz.getPackage().getName(), clazz); } Class<?> enclosingClass = clazz.getEnclosingClass(); if (enclosingClass != null) { getClassPackageNames(enclosingClass, packageNames); } }
java
private static void getClassPackageNames(Class<?> clazz, Map<String, Class<?>> packageNames) { if (isPrivate(clazz)) { throw new IllegalArgumentException(PrettyPrinter.format( "Unable to inject an instance of %s because it is a private class.", clazz)); } else if (!isPublic(clazz)) { packageNames.put(clazz.getPackage().getName(), clazz); } Class<?> enclosingClass = clazz.getEnclosingClass(); if (enclosingClass != null) { getClassPackageNames(enclosingClass, packageNames); } }
[ "private", "static", "void", "getClassPackageNames", "(", "Class", "<", "?", ">", "clazz", ",", "Map", "<", "String", ",", "Class", "<", "?", ">", ">", "packageNames", ")", "{", "if", "(", "isPrivate", "(", "clazz", ")", ")", "{", "throw", "new", "Il...
Visits classes to collect package names. @see {@link #getTypePackageNames}.
[ "Visits", "classes", "to", "collect", "package", "names", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java#L235-L247
36,945
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java
ReflectUtil.getParameterizedTypePackageNames
private static void getParameterizedTypePackageNames(ParameterizedType type, Map<String, Class<?>> packageNames) { for (Type argumentType : type.getActualTypeArguments()) { getTypePackageNames(argumentType, packageNames); } getTypePackageNames(type.getRawType(), packageNames); Type ownerType = type.getOwnerType(); if (ownerType != null) { getTypePackageNames(ownerType, packageNames); } }
java
private static void getParameterizedTypePackageNames(ParameterizedType type, Map<String, Class<?>> packageNames) { for (Type argumentType : type.getActualTypeArguments()) { getTypePackageNames(argumentType, packageNames); } getTypePackageNames(type.getRawType(), packageNames); Type ownerType = type.getOwnerType(); if (ownerType != null) { getTypePackageNames(ownerType, packageNames); } }
[ "private", "static", "void", "getParameterizedTypePackageNames", "(", "ParameterizedType", "type", ",", "Map", "<", "String", ",", "Class", "<", "?", ">", ">", "packageNames", ")", "{", "for", "(", "Type", "argumentType", ":", "type", ".", "getActualTypeArgument...
Visits parameterized types to collect package names. @see {@link #getTypePackageNames}.
[ "Visits", "parameterized", "types", "to", "collect", "package", "names", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java#L254-L265
36,946
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java
ReflectUtil.getTypeVariablePackageNames
private static void getTypeVariablePackageNames(TypeVariable type, Map<String, Class<?>> packageNames) { for (Type boundType : type.getBounds()) { getTypePackageNames(boundType, packageNames); } }
java
private static void getTypeVariablePackageNames(TypeVariable type, Map<String, Class<?>> packageNames) { for (Type boundType : type.getBounds()) { getTypePackageNames(boundType, packageNames); } }
[ "private", "static", "void", "getTypeVariablePackageNames", "(", "TypeVariable", "type", ",", "Map", "<", "String", ",", "Class", "<", "?", ">", ">", "packageNames", ")", "{", "for", "(", "Type", "boundType", ":", "type", ".", "getBounds", "(", ")", ")", ...
Visits type variables to collect package names. @see {@link #getTypeVariablePackageNames}.
[ "Visits", "type", "variables", "to", "collect", "package", "names", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java#L272-L277
36,947
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java
ReflectUtil.getWildcardTypePackageNames
private static void getWildcardTypePackageNames(WildcardType type, Map<String, Class<?>> packageNames) { for (Type boundType : type.getUpperBounds()) { getTypePackageNames(boundType, packageNames); } for (Type boundType : type.getLowerBounds()) { getTypePackageNames(boundType, packageNames); } }
java
private static void getWildcardTypePackageNames(WildcardType type, Map<String, Class<?>> packageNames) { for (Type boundType : type.getUpperBounds()) { getTypePackageNames(boundType, packageNames); } for (Type boundType : type.getLowerBounds()) { getTypePackageNames(boundType, packageNames); } }
[ "private", "static", "void", "getWildcardTypePackageNames", "(", "WildcardType", "type", ",", "Map", "<", "String", ",", "Class", "<", "?", ">", ">", "packageNames", ")", "{", "for", "(", "Type", "boundType", ":", "type", ".", "getUpperBounds", "(", ")", "...
Visits wildcard types to collect package names. @see {@link #getTypeVariablePackageNames}.
[ "Visits", "wildcard", "types", "to", "collect", "package", "names", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/reflect/ReflectUtil.java#L284-L293
36,948
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/binding/ProviderMethodBinding.java
ProviderMethodBinding.getCreationStatements
public SourceSnippet getCreationStatements(NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { String moduleSourceName = ReflectUtil.getSourceName(moduleType); String createModule = "new " + moduleSourceName + "()"; String type = ReflectUtil.getSourceName(targetKey.getTypeLiteral()); return new SourceSnippetBuilder() .append(type).append(" result = ") .append(methodCallUtil.createMethodCallWithInjection(providerMethod, createModule, nameGenerator, methodsOutput)) .build(); }
java
public SourceSnippet getCreationStatements(NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { String moduleSourceName = ReflectUtil.getSourceName(moduleType); String createModule = "new " + moduleSourceName + "()"; String type = ReflectUtil.getSourceName(targetKey.getTypeLiteral()); return new SourceSnippetBuilder() .append(type).append(" result = ") .append(methodCallUtil.createMethodCallWithInjection(providerMethod, createModule, nameGenerator, methodsOutput)) .build(); }
[ "public", "SourceSnippet", "getCreationStatements", "(", "NameGenerator", "nameGenerator", ",", "List", "<", "InjectorMethod", ">", "methodsOutput", ")", "throws", "NoSourceNameException", "{", "String", "moduleSourceName", "=", "ReflectUtil", ".", "getSourceName", "(", ...
provider methods.
[ "provider", "methods", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/binding/ProviderMethodBinding.java#L75-L86
36,949
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/binding/ExposedChildBinding.java
ExposedChildBinding.getGetterMethodPackage
public String getGetterMethodPackage() { Binding childBinding = childBindings.getBinding(key); if (childBinding == null) { // The child binding should exist before we try to expose it! errorManager.logError("No child binding found in %s for %s.", childBindings, key); return ""; } else { return childBinding.getGetterMethodPackage(); } }
java
public String getGetterMethodPackage() { Binding childBinding = childBindings.getBinding(key); if (childBinding == null) { // The child binding should exist before we try to expose it! errorManager.logError("No child binding found in %s for %s.", childBindings, key); return ""; } else { return childBinding.getGetterMethodPackage(); } }
[ "public", "String", "getGetterMethodPackage", "(", ")", "{", "Binding", "childBinding", "=", "childBindings", ".", "getBinding", "(", "key", ")", ";", "if", "(", "childBinding", "==", "null", ")", "{", "// The child binding should exist before we try to expose it!", "...
The getter must be placed in the same package as the child getter, to ensure that its return type is visible.
[ "The", "getter", "must", "be", "placed", "in", "the", "same", "package", "as", "the", "child", "getter", "to", "ensure", "that", "its", "return", "type", "is", "visible", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/binding/ExposedChildBinding.java#L59-L68
36,950
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/binding/ParentBinding.java
ParentBinding.getGetterMethodPackage
public String getGetterMethodPackage() { Binding parentBinding = parentBindings.getBinding(key); if (parentBinding == null) { // The parent binding should exist by the time this is called. errorManager.logError("No parent binding found in %s for %s.", parentBindings, key); return ""; } else { return parentBinding.getGetterMethodPackage(); } }
java
public String getGetterMethodPackage() { Binding parentBinding = parentBindings.getBinding(key); if (parentBinding == null) { // The parent binding should exist by the time this is called. errorManager.logError("No parent binding found in %s for %s.", parentBindings, key); return ""; } else { return parentBinding.getGetterMethodPackage(); } }
[ "public", "String", "getGetterMethodPackage", "(", ")", "{", "Binding", "parentBinding", "=", "parentBindings", ".", "getBinding", "(", "key", ")", ";", "if", "(", "parentBinding", "==", "null", ")", "{", "// The parent binding should exist by the time this is called.",...
The getter must be placed in the same package as the parent getter, to ensure that its return type is visible.
[ "The", "getter", "must", "be", "placed", "in", "the", "same", "package", "as", "the", "parent", "getter", "to", "ensure", "that", "its", "return", "type", "is", "visible", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/binding/ParentBinding.java#L60-L69
36,951
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java
BindingPositioner.getInstallPosition
public GinjectorBindings getInstallPosition(Key<?> key) { Preconditions.checkNotNull(positions, "Must call position before calling getInstallPosition(Key<?>)"); GinjectorBindings position = installOverrides.get(key); if (position == null) { position = positions.get(key); } return position; }
java
public GinjectorBindings getInstallPosition(Key<?> key) { Preconditions.checkNotNull(positions, "Must call position before calling getInstallPosition(Key<?>)"); GinjectorBindings position = installOverrides.get(key); if (position == null) { position = positions.get(key); } return position; }
[ "public", "GinjectorBindings", "getInstallPosition", "(", "Key", "<", "?", ">", "key", ")", "{", "Preconditions", ".", "checkNotNull", "(", "positions", ",", "\"Must call position before calling getInstallPosition(Key<?>)\"", ")", ";", "GinjectorBindings", "position", "="...
Returns the Ginjector where the binding for key should be placed, or null if the key was removed from the dependency graph earlier.
[ "Returns", "the", "Ginjector", "where", "the", "binding", "for", "key", "should", "be", "placed", "or", "null", "if", "the", "key", "was", "removed", "from", "the", "dependency", "graph", "earlier", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java#L126-L134
36,952
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java
BindingPositioner.computeInitialPositions
private void computeInitialPositions() { positions.putAll(output.getPreExistingLocations()); for (Key<?> key : output.getImplicitlyBoundKeys()) { GinjectorBindings initialPosition = computeInitialPosition(key); PrettyPrinter.log(logger, TreeLogger.DEBUG, PrettyPrinter.format( "Initial highest visible position of %s is %s", key, initialPosition)); positions.put(key, initialPosition); } }
java
private void computeInitialPositions() { positions.putAll(output.getPreExistingLocations()); for (Key<?> key : output.getImplicitlyBoundKeys()) { GinjectorBindings initialPosition = computeInitialPosition(key); PrettyPrinter.log(logger, TreeLogger.DEBUG, PrettyPrinter.format( "Initial highest visible position of %s is %s", key, initialPosition)); positions.put(key, initialPosition); } }
[ "private", "void", "computeInitialPositions", "(", ")", "{", "positions", ".", "putAll", "(", "output", ".", "getPreExistingLocations", "(", ")", ")", ";", "for", "(", "Key", "<", "?", ">", "key", ":", "output", ".", "getImplicitlyBoundKeys", "(", ")", ")"...
Place an initial guess in the position map that places each implicit binding as high as possible in the injector tree without causing double binding.
[ "Place", "an", "initial", "guess", "in", "the", "position", "map", "that", "places", "each", "implicit", "binding", "as", "high", "as", "possible", "in", "the", "injector", "tree", "without", "causing", "double", "binding", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java#L146-L156
36,953
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java
BindingPositioner.computeInitialPosition
private GinjectorBindings computeInitialPosition(Key<?> key) { GinjectorBindings initialPosition = output.getGraph().getOrigin(); boolean pinned = initialPosition.isPinned(key); // If the key is pinned (explicitly bound) at the origin, we may be in a situation where we need // to install a binding at the origin, even though we should *use* the binding form a higher // location. // If key is already bound in parent, there is a reason that {@link DependencyExplorer} // chose not to use that binding. Specifically, it implies that the key is exposed to the // parent from the origin. While we are fine using the higher binding, it is still necessary // to install the binding in the origin. if (pinned) { PrettyPrinter.log(logger, TreeLogger.DEBUG, PrettyPrinter.format("Forcing %s to be installed in %s due to a pin.", key, initialPosition)); installOverrides.put(key, initialPosition); } while (canExposeKeyFrom(key, initialPosition, pinned)) { PrettyPrinter.log(logger, TreeLogger.SPAM, "Moving the highest visible position of %s from %s to %s.", key, initialPosition, initialPosition.getParent()); initialPosition = initialPosition.getParent(); } return initialPosition; }
java
private GinjectorBindings computeInitialPosition(Key<?> key) { GinjectorBindings initialPosition = output.getGraph().getOrigin(); boolean pinned = initialPosition.isPinned(key); // If the key is pinned (explicitly bound) at the origin, we may be in a situation where we need // to install a binding at the origin, even though we should *use* the binding form a higher // location. // If key is already bound in parent, there is a reason that {@link DependencyExplorer} // chose not to use that binding. Specifically, it implies that the key is exposed to the // parent from the origin. While we are fine using the higher binding, it is still necessary // to install the binding in the origin. if (pinned) { PrettyPrinter.log(logger, TreeLogger.DEBUG, PrettyPrinter.format("Forcing %s to be installed in %s due to a pin.", key, initialPosition)); installOverrides.put(key, initialPosition); } while (canExposeKeyFrom(key, initialPosition, pinned)) { PrettyPrinter.log(logger, TreeLogger.SPAM, "Moving the highest visible position of %s from %s to %s.", key, initialPosition, initialPosition.getParent()); initialPosition = initialPosition.getParent(); } return initialPosition; }
[ "private", "GinjectorBindings", "computeInitialPosition", "(", "Key", "<", "?", ">", "key", ")", "{", "GinjectorBindings", "initialPosition", "=", "output", ".", "getGraph", "(", ")", ".", "getOrigin", "(", ")", ";", "boolean", "pinned", "=", "initialPosition", ...
Returns the highest injector that we could possibly position the key at without causing a double binding.
[ "Returns", "the", "highest", "injector", "that", "we", "could", "possibly", "position", "the", "key", "at", "without", "causing", "a", "double", "binding", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java#L162-L187
36,954
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java
BindingPositioner.canExposeKeyFrom
private boolean canExposeKeyFrom(Key<?> key, GinjectorBindings child, boolean pinned) { GinjectorBindings parent = child.getParent(); if (parent == null) { // Can't move above the root. return false; } else if (parent.isBoundLocallyInChild(key)) { // If a sibling module already materialized a binding for this key, we // can't float over it. return false; } else if (pinned) { // If a key is pinned, it's visible in the parent iff it has an // ExposedChildBinding pointing at the child. Binding binding = parent.getBinding(key); if (binding == null) { return false; } else if (!(binding instanceof ExposedChildBinding)) { // This should never happen (it would have been caught as a // double-binding earlier). throw new RuntimeException("Unexpected binding shadowing a pinned binding: " + binding); } else { ExposedChildBinding exposedChildBinding = (ExposedChildBinding) binding; if (exposedChildBinding.getChildBindings() != child) { throw new RuntimeException( "Unexpected exposed child binding shadowing a pinned binding: " + binding); } else { return true; } } } else { return true; } }
java
private boolean canExposeKeyFrom(Key<?> key, GinjectorBindings child, boolean pinned) { GinjectorBindings parent = child.getParent(); if (parent == null) { // Can't move above the root. return false; } else if (parent.isBoundLocallyInChild(key)) { // If a sibling module already materialized a binding for this key, we // can't float over it. return false; } else if (pinned) { // If a key is pinned, it's visible in the parent iff it has an // ExposedChildBinding pointing at the child. Binding binding = parent.getBinding(key); if (binding == null) { return false; } else if (!(binding instanceof ExposedChildBinding)) { // This should never happen (it would have been caught as a // double-binding earlier). throw new RuntimeException("Unexpected binding shadowing a pinned binding: " + binding); } else { ExposedChildBinding exposedChildBinding = (ExposedChildBinding) binding; if (exposedChildBinding.getChildBindings() != child) { throw new RuntimeException( "Unexpected exposed child binding shadowing a pinned binding: " + binding); } else { return true; } } } else { return true; } }
[ "private", "boolean", "canExposeKeyFrom", "(", "Key", "<", "?", ">", "key", ",", "GinjectorBindings", "child", ",", "boolean", "pinned", ")", "{", "GinjectorBindings", "parent", "=", "child", ".", "getParent", "(", ")", ";", "if", "(", "parent", "==", "nul...
Tests whether a key from the given child injector can be made visible in its parent. For pinned keys, this means that they're exposed to the parent; for keys that aren't pinned, it means that there's no other constraint preventing them from floating up. <p>Note that "pinned" states whether the key was pinned in the injector it started in; it might not be pinned in child.
[ "Tests", "whether", "a", "key", "from", "the", "given", "child", "injector", "can", "be", "made", "visible", "in", "its", "parent", ".", "For", "pinned", "keys", "this", "means", "that", "they", "re", "exposed", "to", "the", "parent", ";", "for", "keys",...
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java#L198-L230
36,955
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java
BindingPositioner.calculateExactPositions
private void calculateExactPositions() { while (!workqueue.isEmpty()) { Key<?> key = workqueue.iterator().next(); workqueue.remove(key); Set<GinjectorBindings> injectors = getSourceGinjectors(key); injectors.add(positions.get(key)); GinjectorBindings newPosition = lowest(injectors); GinjectorBindings oldPosition = positions.put(key, newPosition); if (oldPosition != newPosition) { PrettyPrinter.log(logger, TreeLogger.DEBUG, "Moved the highest visible position of %s from %s to %s, the lowest injector of %s.", key, oldPosition, newPosition, injectors); // We don't care if GINJECTOR is present, as its Ginjector will resolve to "null", which // will never be reached on the path from the origin up to the root, therefore it won't // actually constrain anything. for (Dependency dependency : output.getGraph().getDependenciesTargeting(key)) { PrettyPrinter.log(logger, TreeLogger.DEBUG, "Re-enqueuing %s due to %s", dependency.getSource(), dependency); workqueue.add(dependency.getSource()); } } } }
java
private void calculateExactPositions() { while (!workqueue.isEmpty()) { Key<?> key = workqueue.iterator().next(); workqueue.remove(key); Set<GinjectorBindings> injectors = getSourceGinjectors(key); injectors.add(positions.get(key)); GinjectorBindings newPosition = lowest(injectors); GinjectorBindings oldPosition = positions.put(key, newPosition); if (oldPosition != newPosition) { PrettyPrinter.log(logger, TreeLogger.DEBUG, "Moved the highest visible position of %s from %s to %s, the lowest injector of %s.", key, oldPosition, newPosition, injectors); // We don't care if GINJECTOR is present, as its Ginjector will resolve to "null", which // will never be reached on the path from the origin up to the root, therefore it won't // actually constrain anything. for (Dependency dependency : output.getGraph().getDependenciesTargeting(key)) { PrettyPrinter.log(logger, TreeLogger.DEBUG, "Re-enqueuing %s due to %s", dependency.getSource(), dependency); workqueue.add(dependency.getSource()); } } } }
[ "private", "void", "calculateExactPositions", "(", ")", "{", "while", "(", "!", "workqueue", ".", "isEmpty", "(", ")", ")", "{", "Key", "<", "?", ">", "key", "=", "workqueue", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "workqueue", ".", ...
Iterates on the position equation, updating each binding in the queue and re-queueing nodes that depend on any node we move. This will always terminate, since we only re-queue when we make a change, and there are a finite number of entries in the injector hierarchy.
[ "Iterates", "on", "the", "position", "equation", "updating", "each", "binding", "in", "the", "queue", "and", "re", "-", "queueing", "nodes", "that", "depend", "on", "any", "node", "we", "move", ".", "This", "will", "always", "terminate", "since", "we", "on...
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java#L237-L262
36,956
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java
BindingPositioner.getSourceGinjectors
private Set<GinjectorBindings> getSourceGinjectors(Key<?> key) { Set<GinjectorBindings> sourceInjectors = new LinkedHashSet<GinjectorBindings>(); for (Dependency dep : output.getGraph().getDependenciesOf(key)) { sourceInjectors.add(positions.get(dep.getTarget())); } return sourceInjectors; }
java
private Set<GinjectorBindings> getSourceGinjectors(Key<?> key) { Set<GinjectorBindings> sourceInjectors = new LinkedHashSet<GinjectorBindings>(); for (Dependency dep : output.getGraph().getDependenciesOf(key)) { sourceInjectors.add(positions.get(dep.getTarget())); } return sourceInjectors; }
[ "private", "Set", "<", "GinjectorBindings", ">", "getSourceGinjectors", "(", "Key", "<", "?", ">", "key", ")", "{", "Set", "<", "GinjectorBindings", ">", "sourceInjectors", "=", "new", "LinkedHashSet", "<", "GinjectorBindings", ">", "(", ")", ";", "for", "("...
Returns the injectors where the dependencies for node are currently placed.
[ "Returns", "the", "injectors", "where", "the", "dependencies", "for", "node", "are", "currently", "placed", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/BindingPositioner.java#L267-L273
36,957
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceSnippets.java
SourceSnippets.callChildGetter
public static SourceSnippet callChildGetter(final GinjectorBindings childBindings, final Key<?> key) { return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { return writeContext.callChildGetter(childBindings, key); } }; }
java
public static SourceSnippet callChildGetter(final GinjectorBindings childBindings, final Key<?> key) { return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { return writeContext.callChildGetter(childBindings, key); } }; }
[ "public", "static", "SourceSnippet", "callChildGetter", "(", "final", "GinjectorBindings", "childBindings", ",", "final", "Key", "<", "?", ">", "key", ")", "{", "return", "new", "SourceSnippet", "(", ")", "{", "public", "String", "getSource", "(", "InjectorWrite...
Creates a snippet that evaluates to an injected instance of the given key, as produced by the given child.
[ "Creates", "a", "snippet", "that", "evaluates", "to", "an", "injected", "instance", "of", "the", "given", "key", "as", "produced", "by", "the", "given", "child", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceSnippets.java#L34-L41
36,958
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceSnippets.java
SourceSnippets.callMethod
public static SourceSnippet callMethod(final String methodName, final String fragmentPackageName, final Iterable<String> parameters) { return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { return writeContext.callMethod(methodName, fragmentPackageName, parameters); } }; }
java
public static SourceSnippet callMethod(final String methodName, final String fragmentPackageName, final Iterable<String> parameters) { return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { return writeContext.callMethod(methodName, fragmentPackageName, parameters); } }; }
[ "public", "static", "SourceSnippet", "callMethod", "(", "final", "String", "methodName", ",", "final", "String", "fragmentPackageName", ",", "final", "Iterable", "<", "String", ">", "parameters", ")", "{", "return", "new", "SourceSnippet", "(", ")", "{", "public...
Creates a snippet that evaluates to an invocation of the named method on the given package fragment. <p>Used when generating an intermediate invoker method; see {@link MethodCallUtil#createMethodCallWithInjection}.
[ "Creates", "a", "snippet", "that", "evaluates", "to", "an", "invocation", "of", "the", "named", "method", "on", "the", "given", "package", "fragment", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceSnippets.java#L78-L85
36,959
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceSnippets.java
SourceSnippets.callParentGetter
public static SourceSnippet callParentGetter(final Key<?> key, final GinjectorBindings parentBindings) { return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { return writeContext.callParentGetter(key, parentBindings); } }; }
java
public static SourceSnippet callParentGetter(final Key<?> key, final GinjectorBindings parentBindings) { return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { return writeContext.callParentGetter(key, parentBindings); } }; }
[ "public", "static", "SourceSnippet", "callParentGetter", "(", "final", "Key", "<", "?", ">", "key", ",", "final", "GinjectorBindings", "parentBindings", ")", "{", "return", "new", "SourceSnippet", "(", ")", "{", "public", "String", "getSource", "(", "InjectorWri...
Creates a snippet that evaluates to an injected instance of the given key, as produced by the given parent injector.
[ "Creates", "a", "snippet", "that", "evaluates", "to", "an", "injected", "instance", "of", "the", "given", "key", "as", "produced", "by", "the", "given", "parent", "injector", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceSnippets.java#L91-L98
36,960
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceSnippets.java
SourceSnippets.forText
public static SourceSnippet forText(final String text) { return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { return text; } }; }
java
public static SourceSnippet forText(final String text) { return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { return text; } }; }
[ "public", "static", "SourceSnippet", "forText", "(", "final", "String", "text", ")", "{", "return", "new", "SourceSnippet", "(", ")", "{", "public", "String", "getSource", "(", "InjectorWriteContext", "writeContext", ")", "{", "return", "text", ";", "}", "}", ...
Creates a snippet that generates a constant text string.
[ "Creates", "a", "snippet", "that", "generates", "a", "constant", "text", "string", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceSnippets.java#L115-L121
36,961
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/NameGenerator.java
NameGenerator.getFragmentClassName
public String getFragmentClassName(String injectorClassName, FragmentPackageName fragmentPackageName) { // Sanity check. Preconditions.checkArgument(!injectorClassName.contains("."), "The injector class must be a simple name, but it was \"%s\"", injectorClassName); // Note that the fragment package name is not actually included in the // fragment. This reduces the length of the fragment's class name, which is // important because some systems have small limits on the maximum length of // a file (e.g., ~256 characters). However, it means that other parts of // Gin must reference the fragment using its canonical class name, to avoid // ambiguity. return injectorClassName + "_fragment"; }
java
public String getFragmentClassName(String injectorClassName, FragmentPackageName fragmentPackageName) { // Sanity check. Preconditions.checkArgument(!injectorClassName.contains("."), "The injector class must be a simple name, but it was \"%s\"", injectorClassName); // Note that the fragment package name is not actually included in the // fragment. This reduces the length of the fragment's class name, which is // important because some systems have small limits on the maximum length of // a file (e.g., ~256 characters). However, it means that other parts of // Gin must reference the fragment using its canonical class name, to avoid // ambiguity. return injectorClassName + "_fragment"; }
[ "public", "String", "getFragmentClassName", "(", "String", "injectorClassName", ",", "FragmentPackageName", "fragmentPackageName", ")", "{", "// Sanity check.", "Preconditions", ".", "checkArgument", "(", "!", "injectorClassName", ".", "contains", "(", "\".\"", ")", ","...
Computes the name of a single fragment of a Ginjector. @param injectorClassName the simple name of the injector's class (not including its package)
[ "Computes", "the", "name", "of", "a", "single", "fragment", "of", "a", "Ginjector", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/NameGenerator.java#L104-L117
36,962
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/NameGenerator.java
NameGenerator.replaceLast
public static String replaceLast(String source, char toReplace, char with) { StringBuilder sb = new StringBuilder(source); int index = sb.lastIndexOf(String.valueOf(toReplace)); if (index != -1) { sb.setCharAt(index, with); } return sb.toString(); }
java
public static String replaceLast(String source, char toReplace, char with) { StringBuilder sb = new StringBuilder(source); int index = sb.lastIndexOf(String.valueOf(toReplace)); if (index != -1) { sb.setCharAt(index, with); } return sb.toString(); }
[ "public", "static", "String", "replaceLast", "(", "String", "source", ",", "char", "toReplace", ",", "char", "with", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "source", ")", ";", "int", "index", "=", "sb", ".", "lastIndexOf", "(", ...
Static for access from enum.
[ "Static", "for", "access", "from", "enum", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/NameGenerator.java#L225-L232
36,963
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/DependencyExplorer.java
DependencyExplorer.explore
public DependencyExplorerOutput explore(GinjectorBindings origin) { DependencyExplorerOutput output = new DependencyExplorerOutput(); DependencyGraph.Builder builder = new DependencyGraph.Builder(origin); for (Dependency edge : origin.getDependencies()) { Preconditions.checkState( Dependency.GINJECTOR.equals(edge.getSource()) || origin.isBound(edge.getSource()), "Expected non-null source %s to be bound in origin!", edge.getSource()); builder.addEdge(edge); if (!edge.getSource().equals(Dependency.GINJECTOR) && visited.add(edge.getSource())) { // Need to register where we can find the "source". Note that this will be always be // available somewhere, because it's already available at the origin (that's how we found // this dependency). PrettyPrinter.log(logger, TreeLogger.DEBUG, "Registering %s as available at %s because of the dependency %s", edge.getSource(), origin, edge); output.preExistingBindings.put(edge.getSource(), locateHighestAccessibleSource(edge.getSource(), origin)); } PrettyPrinter.log(logger, TreeLogger.DEBUG, "Exploring from %s in %s because of the dependency %s", edge.getTarget(), origin, edge); // Visit the target of the dependency to find additional bindings visit(edge.getTarget(), builder, output, origin); } output.setGraph(builder.build()); return output; }
java
public DependencyExplorerOutput explore(GinjectorBindings origin) { DependencyExplorerOutput output = new DependencyExplorerOutput(); DependencyGraph.Builder builder = new DependencyGraph.Builder(origin); for (Dependency edge : origin.getDependencies()) { Preconditions.checkState( Dependency.GINJECTOR.equals(edge.getSource()) || origin.isBound(edge.getSource()), "Expected non-null source %s to be bound in origin!", edge.getSource()); builder.addEdge(edge); if (!edge.getSource().equals(Dependency.GINJECTOR) && visited.add(edge.getSource())) { // Need to register where we can find the "source". Note that this will be always be // available somewhere, because it's already available at the origin (that's how we found // this dependency). PrettyPrinter.log(logger, TreeLogger.DEBUG, "Registering %s as available at %s because of the dependency %s", edge.getSource(), origin, edge); output.preExistingBindings.put(edge.getSource(), locateHighestAccessibleSource(edge.getSource(), origin)); } PrettyPrinter.log(logger, TreeLogger.DEBUG, "Exploring from %s in %s because of the dependency %s", edge.getTarget(), origin, edge); // Visit the target of the dependency to find additional bindings visit(edge.getTarget(), builder, output, origin); } output.setGraph(builder.build()); return output; }
[ "public", "DependencyExplorerOutput", "explore", "(", "GinjectorBindings", "origin", ")", "{", "DependencyExplorerOutput", "output", "=", "new", "DependencyExplorerOutput", "(", ")", ";", "DependencyGraph", ".", "Builder", "builder", "=", "new", "DependencyGraph", ".", ...
Explore the unresolved dependencies in the origin Ginjector, and create the corresponding dependency graph. Also gathers information about key in the dependency graph, such as which Ginjector it is already available on, or what implicit binding was created for it. @param origin the ginjector to build a dependency graph for
[ "Explore", "the", "unresolved", "dependencies", "in", "the", "origin", "Ginjector", "and", "create", "the", "corresponding", "dependency", "graph", ".", "Also", "gathers", "information", "about", "key", "in", "the", "dependency", "graph", "such", "as", "which", ...
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/DependencyExplorer.java#L65-L93
36,964
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/DependencyExplorer.java
DependencyExplorer.locateHighestAccessibleSource
private GinjectorBindings locateHighestAccessibleSource(Key<?> key, GinjectorBindings origin) { // If we don't already have a binding, and the key is "pinned", it means that this injector // is supposed to contain a binding, but it needs to have one created implicitly. We return // null so that we attempt to create the implicit binding. if (!origin.isBound(key) && origin.isPinned(key)) { return null; } GinjectorBindings source = null; for (GinjectorBindings iter = origin; iter != null; iter = iter.getParent()) { // If the key is already explicitly bound, or has a pin indicating that it // will be explicitly bound once it gets visited (we visit children before // parents) then we can access the binding from the given location. if (iter.isBound(key) || iter.isPinned(key)) { source = iter; } } return source; }
java
private GinjectorBindings locateHighestAccessibleSource(Key<?> key, GinjectorBindings origin) { // If we don't already have a binding, and the key is "pinned", it means that this injector // is supposed to contain a binding, but it needs to have one created implicitly. We return // null so that we attempt to create the implicit binding. if (!origin.isBound(key) && origin.isPinned(key)) { return null; } GinjectorBindings source = null; for (GinjectorBindings iter = origin; iter != null; iter = iter.getParent()) { // If the key is already explicitly bound, or has a pin indicating that it // will be explicitly bound once it gets visited (we visit children before // parents) then we can access the binding from the given location. if (iter.isBound(key) || iter.isPinned(key)) { source = iter; } } return source; }
[ "private", "GinjectorBindings", "locateHighestAccessibleSource", "(", "Key", "<", "?", ">", "key", ",", "GinjectorBindings", "origin", ")", "{", "// If we don't already have a binding, and the key is \"pinned\", it means that this injector", "// is supposed to contain a binding, but it...
Find the highest binding in the Ginjector tree that could be used to supply the given key. <p>This takes care not to use a higher parent binding if the parent only has the binding because its exposed from this Ginjector. This leads to problems because the resolution algorithm won't actually create the binding here if it can just use a parents binding. @param key The binding to search for @return the highest ginjector that contains the key or {@code null} if none contain it
[ "Find", "the", "highest", "binding", "in", "the", "Ginjector", "tree", "that", "could", "be", "used", "to", "supply", "the", "given", "key", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/DependencyExplorer.java#L139-L157
36,965
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/EagerCycleFinder.java
EagerCycleFinder.findAndReportCycles
public boolean findAndReportCycles(DependencyGraph graph) { this.graph = graph; cycleDetected = false; visitedEdge = new LinkedHashMap<Key<?>, Dependency>(graph.size()); for (Key<?> key : graph.getAllKeys()) { visit(key, null); } return cycleDetected; }
java
public boolean findAndReportCycles(DependencyGraph graph) { this.graph = graph; cycleDetected = false; visitedEdge = new LinkedHashMap<Key<?>, Dependency>(graph.size()); for (Key<?> key : graph.getAllKeys()) { visit(key, null); } return cycleDetected; }
[ "public", "boolean", "findAndReportCycles", "(", "DependencyGraph", "graph", ")", "{", "this", ".", "graph", "=", "graph", ";", "cycleDetected", "=", "false", ";", "visitedEdge", "=", "new", "LinkedHashMap", "<", "Key", "<", "?", ">", ",", "Dependency", ">",...
Detects cycles in the given graph. @return {@code true} if any cycles were detected
[ "Detects", "cycles", "in", "the", "given", "graph", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/EagerCycleFinder.java#L72-L82
36,966
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/EagerCycleFinder.java
EagerCycleFinder.rootCycleAt
static List<Dependency> rootCycleAt(List<Dependency> cycle, Key<?> key) { for (int i = 0; i < cycle.size(); ++i) { if (key.equals(cycle.get(i).getSource())) { List<Dependency> returnValue = new ArrayList<Dependency>(); returnValue.addAll(cycle.subList(i, cycle.size())); returnValue.addAll(cycle.subList(0, i)); return returnValue; } } return cycle; }
java
static List<Dependency> rootCycleAt(List<Dependency> cycle, Key<?> key) { for (int i = 0; i < cycle.size(); ++i) { if (key.equals(cycle.get(i).getSource())) { List<Dependency> returnValue = new ArrayList<Dependency>(); returnValue.addAll(cycle.subList(i, cycle.size())); returnValue.addAll(cycle.subList(0, i)); return returnValue; } } return cycle; }
[ "static", "List", "<", "Dependency", ">", "rootCycleAt", "(", "List", "<", "Dependency", ">", "cycle", ",", "Key", "<", "?", ">", "key", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "cycle", ".", "size", "(", ")", ";", "++", "i", ...
Attempts to root the given dependency cycle at the given key. If the key is present in the cycle, rotates the dependency cycle so that the key is the first source. Otherwise, returns the cycle unchanged.
[ "Attempts", "to", "root", "the", "given", "dependency", "cycle", "at", "the", "given", "key", ".", "If", "the", "key", "is", "present", "in", "the", "cycle", "rotates", "the", "dependency", "cycle", "so", "that", "the", "key", "is", "the", "first", "sour...
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/EagerCycleFinder.java#L143-L154
36,967
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/reflect/MethodLiteral.java
MethodLiteral.getParameterTypes
public List<TypeLiteral<?>> getParameterTypes() { if (parameterTypes == null) { parameterTypes = getDeclaringType().getParameterTypes(getMember()); } return parameterTypes; }
java
public List<TypeLiteral<?>> getParameterTypes() { if (parameterTypes == null) { parameterTypes = getDeclaringType().getParameterTypes(getMember()); } return parameterTypes; }
[ "public", "List", "<", "TypeLiteral", "<", "?", ">", ">", "getParameterTypes", "(", ")", "{", "if", "(", "parameterTypes", "==", "null", ")", "{", "parameterTypes", "=", "getDeclaringType", "(", ")", ".", "getParameterTypes", "(", "getMember", "(", ")", ")...
Returns this method's parameter types, if appropriate parametrized with the declaring class's type parameters. @return parameter types
[ "Returns", "this", "method", "s", "parameter", "types", "if", "appropriate", "parametrized", "with", "the", "declaring", "class", "s", "type", "parameters", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/reflect/MethodLiteral.java#L116-L121
36,968
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/GinjectorGenerator.java
GinjectorGenerator.createGinClassLoader
private ClassLoader createGinClassLoader(TreeLogger logger, GeneratorContext context) { Set<String> exceptions = new LinkedHashSet<String>(); exceptions.add("com.google.inject"); // Need the non-super-source version during generation. exceptions.add("javax.inject"); // Need the non-super-source version during generation. exceptions.add("com.google.gwt.inject.client"); // Excluded to allow class-literal comparison. // Required by GWT 2.8.0+ to prevent loading of GWT script only java.lang.JsException class // See: https://github.com/gwtproject/gwt/issues/9311 // See: https://github.com/gwtproject/gwt/commit/1d660d2fc00a5cbfeccf512251f78ab4302ab633 exceptions.add("com.google.gwt.core.client"); exceptions.add("com.google.gwt.core.client.impl"); // Add any excepted packages or classes registered by other developers. exceptions.addAll(getValuesForProperty("gin.classloading.exceptedPackages")); return new GinBridgeClassLoader(context, logger, exceptions); }
java
private ClassLoader createGinClassLoader(TreeLogger logger, GeneratorContext context) { Set<String> exceptions = new LinkedHashSet<String>(); exceptions.add("com.google.inject"); // Need the non-super-source version during generation. exceptions.add("javax.inject"); // Need the non-super-source version during generation. exceptions.add("com.google.gwt.inject.client"); // Excluded to allow class-literal comparison. // Required by GWT 2.8.0+ to prevent loading of GWT script only java.lang.JsException class // See: https://github.com/gwtproject/gwt/issues/9311 // See: https://github.com/gwtproject/gwt/commit/1d660d2fc00a5cbfeccf512251f78ab4302ab633 exceptions.add("com.google.gwt.core.client"); exceptions.add("com.google.gwt.core.client.impl"); // Add any excepted packages or classes registered by other developers. exceptions.addAll(getValuesForProperty("gin.classloading.exceptedPackages")); return new GinBridgeClassLoader(context, logger, exceptions); }
[ "private", "ClassLoader", "createGinClassLoader", "(", "TreeLogger", "logger", ",", "GeneratorContext", "context", ")", "{", "Set", "<", "String", ">", "exceptions", "=", "new", "LinkedHashSet", "<", "String", ">", "(", ")", ";", "exceptions", ".", "add", "(",...
Creates a new gin-specific class loader that will load GWT and non-GWT types such that there is never a conflict, especially with super source. @param logger logger for errors that occur during class loading @param context generator context in which classes are loaded @return new gin class loader @see GinBridgeClassLoader
[ "Creates", "a", "new", "gin", "-", "specific", "class", "loader", "that", "will", "load", "GWT", "and", "non", "-", "GWT", "types", "such", "that", "there", "is", "never", "a", "conflict", "especially", "with", "super", "source", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/GinjectorGenerator.java#L86-L101
36,969
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/GinjectorGenerator.java
GinjectorGenerator.loadClass
Class<?> loadClass(String requestedClass, boolean initialize) throws ClassNotFoundException { String binaryName = requestedClass; while (true) { try { return Class.forName(binaryName, initialize, classLoader); } catch (ClassNotFoundException e) { if (!binaryName.contains(".")) { throw e; } else { binaryName = replaceLastPeriodWithDollar(binaryName); } } } }
java
Class<?> loadClass(String requestedClass, boolean initialize) throws ClassNotFoundException { String binaryName = requestedClass; while (true) { try { return Class.forName(binaryName, initialize, classLoader); } catch (ClassNotFoundException e) { if (!binaryName.contains(".")) { throw e; } else { binaryName = replaceLastPeriodWithDollar(binaryName); } } } }
[ "Class", "<", "?", ">", "loadClass", "(", "String", "requestedClass", ",", "boolean", "initialize", ")", "throws", "ClassNotFoundException", "{", "String", "binaryName", "=", "requestedClass", ";", "while", "(", "true", ")", "{", "try", "{", "return", "Class",...
Package accessible for testing.
[ "Package", "accessible", "for", "testing", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/GinjectorGenerator.java#L225-L238
36,970
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java
GinjectorBindingsOutputter.write
void write(GinjectorBindings bindings) throws UnableToCompleteException { TypeLiteral<?> ginjectorInterface = bindings.getGinjectorInterface(); String implClassName = ginjectorNameGenerator.getClassName(bindings); if (implClassName.contains(".")) { errorManager.logError("Internal error: the injector class name \"%s\" contains a full stop.", implClassName); } String packageName = ReflectUtil.getUserPackageName(TypeLiteral.get(bindings.getModule())); PrintWriter printWriter = ctx.tryCreate(logger, packageName, implClassName); if (printWriter == null) { // We already created this Ginjector. return; } ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, implClassName); SourceWriter writer = composerFactory.createSourceWriter(ctx, printWriter); FragmentMap fragments = new FragmentMap(bindings, packageName, implClassName, fragmentOutputterFactory); outputBindings(bindings, fragments, writer); errorManager.checkForError(); fragments.commitAll(); writer.commit(logger); }
java
void write(GinjectorBindings bindings) throws UnableToCompleteException { TypeLiteral<?> ginjectorInterface = bindings.getGinjectorInterface(); String implClassName = ginjectorNameGenerator.getClassName(bindings); if (implClassName.contains(".")) { errorManager.logError("Internal error: the injector class name \"%s\" contains a full stop.", implClassName); } String packageName = ReflectUtil.getUserPackageName(TypeLiteral.get(bindings.getModule())); PrintWriter printWriter = ctx.tryCreate(logger, packageName, implClassName); if (printWriter == null) { // We already created this Ginjector. return; } ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, implClassName); SourceWriter writer = composerFactory.createSourceWriter(ctx, printWriter); FragmentMap fragments = new FragmentMap(bindings, packageName, implClassName, fragmentOutputterFactory); outputBindings(bindings, fragments, writer); errorManager.checkForError(); fragments.commitAll(); writer.commit(logger); }
[ "void", "write", "(", "GinjectorBindings", "bindings", ")", "throws", "UnableToCompleteException", "{", "TypeLiteral", "<", "?", ">", "ginjectorInterface", "=", "bindings", ".", "getGinjectorInterface", "(", ")", ";", "String", "implClassName", "=", "ginjectorNameGene...
Writes the Ginjector class for the given bindings object, and all its package-specific fragments.
[ "Writes", "the", "Ginjector", "class", "for", "the", "given", "bindings", "object", "and", "all", "its", "package", "-", "specific", "fragments", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java#L95-L123
36,971
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java
GinjectorBindingsOutputter.outputInterfaceField
private void outputInterfaceField(GinjectorBindings bindings, SourceWriteUtil sourceWriteUtil, SourceWriter writer) { // Only the root injector has an interface binding. if (bindings.getParent() != null) { return; } Class<?> boundGinjectorInterface = getBoundGinjector(bindings); if (boundGinjectorInterface == null) { // Sanity-check: if this fails, then we somehow didn't bind the injector // interface in the root module (the root module should always generate a // binding for the injector). errorManager.logError("Injector interface not bound in the root module."); return; } NameGenerator nameGenerator = bindings.getNameGenerator(); String fieldName = nameGenerator.getGinjectorInterfaceFieldName(); String getterName = nameGenerator.getGinjectorInterfaceGetterMethodName(); writer.beginJavaDocComment(); writer.print("The implementation of " + boundGinjectorInterface); writer.endJavaDocComment(); writer.println("private final %s %s;", boundGinjectorInterface.getCanonicalName(), fieldName); sourceWriteUtil.writeMethod(writer, String.format("public %s %s()", boundGinjectorInterface.getCanonicalName(), getterName), String.format("return %s;", fieldName)); }
java
private void outputInterfaceField(GinjectorBindings bindings, SourceWriteUtil sourceWriteUtil, SourceWriter writer) { // Only the root injector has an interface binding. if (bindings.getParent() != null) { return; } Class<?> boundGinjectorInterface = getBoundGinjector(bindings); if (boundGinjectorInterface == null) { // Sanity-check: if this fails, then we somehow didn't bind the injector // interface in the root module (the root module should always generate a // binding for the injector). errorManager.logError("Injector interface not bound in the root module."); return; } NameGenerator nameGenerator = bindings.getNameGenerator(); String fieldName = nameGenerator.getGinjectorInterfaceFieldName(); String getterName = nameGenerator.getGinjectorInterfaceGetterMethodName(); writer.beginJavaDocComment(); writer.print("The implementation of " + boundGinjectorInterface); writer.endJavaDocComment(); writer.println("private final %s %s;", boundGinjectorInterface.getCanonicalName(), fieldName); sourceWriteUtil.writeMethod(writer, String.format("public %s %s()", boundGinjectorInterface.getCanonicalName(), getterName), String.format("return %s;", fieldName)); }
[ "private", "void", "outputInterfaceField", "(", "GinjectorBindings", "bindings", ",", "SourceWriteUtil", "sourceWriteUtil", ",", "SourceWriter", "writer", ")", "{", "// Only the root injector has an interface binding.", "if", "(", "bindings", ".", "getParent", "(", ")", "...
Writes code to store and retrieve the current injector interface, if one is bound.
[ "Writes", "code", "to", "store", "and", "retrieve", "the", "current", "injector", "interface", "if", "one", "is", "bound", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java#L219-L249
36,972
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java
GinjectorBindingsOutputter.outputMemberInjections
private void outputMemberInjections(GinjectorBindings bindings, FragmentMap fragments, SourceWriteUtil sourceWriteUtil) { NameGenerator nameGenerator = bindings.getNameGenerator(); for (TypeLiteral<?> type : bindings.getMemberInjectRequests()) { if (!reachabilityAnalyzer.isReachableMemberInject(bindings, type)) { continue; } List<InjectorMethod> memberInjectionHelpers = new ArrayList<InjectorMethod>(); try { sourceWriteUtil.createMemberInjection(type, nameGenerator, memberInjectionHelpers); outputMethods(memberInjectionHelpers, fragments); } catch (NoSourceNameException e) { errorManager.logError(e.getMessage(), e); } } }
java
private void outputMemberInjections(GinjectorBindings bindings, FragmentMap fragments, SourceWriteUtil sourceWriteUtil) { NameGenerator nameGenerator = bindings.getNameGenerator(); for (TypeLiteral<?> type : bindings.getMemberInjectRequests()) { if (!reachabilityAnalyzer.isReachableMemberInject(bindings, type)) { continue; } List<InjectorMethod> memberInjectionHelpers = new ArrayList<InjectorMethod>(); try { sourceWriteUtil.createMemberInjection(type, nameGenerator, memberInjectionHelpers); outputMethods(memberInjectionHelpers, fragments); } catch (NoSourceNameException e) { errorManager.logError(e.getMessage(), e); } } }
[ "private", "void", "outputMemberInjections", "(", "GinjectorBindings", "bindings", ",", "FragmentMap", "fragments", ",", "SourceWriteUtil", "sourceWriteUtil", ")", "{", "NameGenerator", "nameGenerator", "=", "bindings", ".", "getNameGenerator", "(", ")", ";", "for", "...
Adds member injections to each fragment.
[ "Adds", "member", "injections", "to", "each", "fragment", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java#L300-L317
36,973
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java
GinjectorBindingsOutputter.outputStaticInjectionMethods
void outputStaticInjectionMethods(Class<?> type, FragmentMap fragments, NameGenerator nameGenerator, SourceWriteUtil sourceWriteUtil) { String methodName = nameGenerator.convertToValidMemberName("injectStatic_" + type.getName()); SourceSnippetBuilder body = new SourceSnippetBuilder(); for (InjectionPoint injectionPoint : InjectionPoint.forStaticMethodsAndFields(type)) { Member member = injectionPoint.getMember(); try { List<InjectorMethod> staticInjectionHelpers = new ArrayList<InjectorMethod>(); if (member instanceof Method) { MethodLiteral<?, Method> method = MethodLiteral.get((Method) member, TypeLiteral.get(member.getDeclaringClass())); body.append(methodCallUtil.createMethodCallWithInjection(method, null, nameGenerator, staticInjectionHelpers)); } else if (member instanceof Field) { FieldLiteral<?> field = FieldLiteral.get((Field) member, TypeLiteral.get(member.getDeclaringClass())); body.append(sourceWriteUtil.createFieldInjection(field, null, nameGenerator, staticInjectionHelpers)); } outputMethods(staticInjectionHelpers, fragments); } catch (NoSourceNameException e) { errorManager.logError(e.getMessage(), e); } } // Note that the top-level method that performs static injection will only // invoke a bunch of other injector methods. Therefore, it doesn't matter // which package it goes in, and we don't need to invoke getUserPackageName // (which is good, because in practice users statically inject types that // have no user package name because they're private inner classes!) String packageName = type.getPackage().getName(); InjectorMethod method = SourceSnippets.asMethod(false, "private void " + methodName + "()", packageName, body.build()); GinjectorFragmentOutputter fragment = fragments.get(fragmentPackageNameFactory.create(packageName)); fragment.outputMethod(method); fragment.invokeInInitializeStaticInjections(methodName); }
java
void outputStaticInjectionMethods(Class<?> type, FragmentMap fragments, NameGenerator nameGenerator, SourceWriteUtil sourceWriteUtil) { String methodName = nameGenerator.convertToValidMemberName("injectStatic_" + type.getName()); SourceSnippetBuilder body = new SourceSnippetBuilder(); for (InjectionPoint injectionPoint : InjectionPoint.forStaticMethodsAndFields(type)) { Member member = injectionPoint.getMember(); try { List<InjectorMethod> staticInjectionHelpers = new ArrayList<InjectorMethod>(); if (member instanceof Method) { MethodLiteral<?, Method> method = MethodLiteral.get((Method) member, TypeLiteral.get(member.getDeclaringClass())); body.append(methodCallUtil.createMethodCallWithInjection(method, null, nameGenerator, staticInjectionHelpers)); } else if (member instanceof Field) { FieldLiteral<?> field = FieldLiteral.get((Field) member, TypeLiteral.get(member.getDeclaringClass())); body.append(sourceWriteUtil.createFieldInjection(field, null, nameGenerator, staticInjectionHelpers)); } outputMethods(staticInjectionHelpers, fragments); } catch (NoSourceNameException e) { errorManager.logError(e.getMessage(), e); } } // Note that the top-level method that performs static injection will only // invoke a bunch of other injector methods. Therefore, it doesn't matter // which package it goes in, and we don't need to invoke getUserPackageName // (which is good, because in practice users statically inject types that // have no user package name because they're private inner classes!) String packageName = type.getPackage().getName(); InjectorMethod method = SourceSnippets.asMethod(false, "private void " + methodName + "()", packageName, body.build()); GinjectorFragmentOutputter fragment = fragments.get(fragmentPackageNameFactory.create(packageName)); fragment.outputMethod(method); fragment.invokeInInitializeStaticInjections(methodName); }
[ "void", "outputStaticInjectionMethods", "(", "Class", "<", "?", ">", "type", ",", "FragmentMap", "fragments", ",", "NameGenerator", "nameGenerator", ",", "SourceWriteUtil", "sourceWriteUtil", ")", "{", "String", "methodName", "=", "nameGenerator", ".", "convertToValid...
Outputs all the static injection methods for the given class.
[ "Outputs", "all", "the", "static", "injection", "methods", "for", "the", "given", "class", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java#L329-L368
36,974
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java
GinjectorBindingsOutputter.outputMethods
void outputMethods(Iterable<InjectorMethod> methods, FragmentMap fragments) { for (InjectorMethod method : methods) { FragmentPackageName fragmentPackageName = fragmentPackageNameFactory.create(method.getPackageName()); GinjectorFragmentOutputter fragment = fragments.get(fragmentPackageName); fragment.outputMethod(method); } }
java
void outputMethods(Iterable<InjectorMethod> methods, FragmentMap fragments) { for (InjectorMethod method : methods) { FragmentPackageName fragmentPackageName = fragmentPackageNameFactory.create(method.getPackageName()); GinjectorFragmentOutputter fragment = fragments.get(fragmentPackageName); fragment.outputMethod(method); } }
[ "void", "outputMethods", "(", "Iterable", "<", "InjectorMethod", ">", "methods", ",", "FragmentMap", "fragments", ")", "{", "for", "(", "InjectorMethod", "method", ":", "methods", ")", "{", "FragmentPackageName", "fragmentPackageName", "=", "fragmentPackageNameFactory...
Outputs some methods to the fragments they belong to.
[ "Outputs", "some", "methods", "to", "the", "fragments", "they", "belong", "to", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java#L373-L380
36,975
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java
GinjectorBindingsOutputter.getBoundGinjector
private static Class<?> getBoundGinjector(GinjectorBindings bindings) { if (bindings.getGinjectorInterface() == null) { return null; } TypeLiteral<?> ginjectorInterface = bindings.getGinjectorInterface(); Key<?> ginjectorKey = Key.get(ginjectorInterface); if (!bindings.isBound(ginjectorKey)) { return null; } if (!(bindings.getBinding(ginjectorKey) instanceof GinjectorBinding)) { return null; } return ginjectorInterface.getRawType(); }
java
private static Class<?> getBoundGinjector(GinjectorBindings bindings) { if (bindings.getGinjectorInterface() == null) { return null; } TypeLiteral<?> ginjectorInterface = bindings.getGinjectorInterface(); Key<?> ginjectorKey = Key.get(ginjectorInterface); if (!bindings.isBound(ginjectorKey)) { return null; } if (!(bindings.getBinding(ginjectorKey) instanceof GinjectorBinding)) { return null; } return ginjectorInterface.getRawType(); }
[ "private", "static", "Class", "<", "?", ">", "getBoundGinjector", "(", "GinjectorBindings", "bindings", ")", "{", "if", "(", "bindings", ".", "getGinjectorInterface", "(", ")", "==", "null", ")", "{", "return", "null", ";", "}", "TypeLiteral", "<", "?", ">...
Gets the Ginjector interface that is bound by the given bindings, if any.
[ "Gets", "the", "Ginjector", "interface", "that", "is", "bound", "by", "the", "given", "bindings", "if", "any", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/output/GinjectorBindingsOutputter.java#L405-L423
36,976
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/output/GinjectorFragmentOutputter.java
GinjectorFragmentOutputter.writeBindingGetter
void writeBindingGetter(Key<?> key, Binding binding, GinScope scope, List<InjectorMethod> helperMethodsOutput) { Context bindingContext = binding.getContext(); SourceSnippetBuilder getterBuilder = new SourceSnippetBuilder(); SourceSnippet creationStatements; String getter = nameGenerator.getGetterMethodName(key); String typeName; try { typeName = ReflectUtil.getSourceName(key.getTypeLiteral()); creationStatements = binding.getCreationStatements(nameGenerator, helperMethodsOutput); } catch (NoSourceNameException e) { errorManager.logError("Error trying to write getter for [%s] -> [%s];" + " binding declaration: %s", e, key, binding, bindingContext); return; } // Name of the field that we might need. String field = nameGenerator.getSingletonFieldName(key); switch (scope) { case EAGER_SINGLETON: initializeEagerSingletonsBody.append("// Eager singleton bound at:\n"); appendBindingContextCommentToMethod(bindingContext, initializeEagerSingletonsBody); initializeEagerSingletonsBody.append(getter).append("();\n"); // !break //CHECKSTYLE_OFF case SINGLETON: //CHECKSTYLE_OFF writer.println("private " + typeName + " " + field + " = null;"); writer.println(); getterBuilder.append(String.format("\nif (%s == null) {\n", field)) .append(creationStatements).append("\n") .append(String.format(" %s = result;\n", field)) .append("}\n") .append(String.format("return %s;\n", field)); break; case NO_SCOPE: sourceWriteUtil.writeBindingContextJavadoc(writer, bindingContext, key); getterBuilder.append(creationStatements).append("\n").append("return result;\n"); break; default: throw new IllegalStateException(); } outputMethod(SourceSnippets.asMethod(false, String.format("public %s %s()", typeName, getter), fragmentPackageName.toString(), getterBuilder.build())); }
java
void writeBindingGetter(Key<?> key, Binding binding, GinScope scope, List<InjectorMethod> helperMethodsOutput) { Context bindingContext = binding.getContext(); SourceSnippetBuilder getterBuilder = new SourceSnippetBuilder(); SourceSnippet creationStatements; String getter = nameGenerator.getGetterMethodName(key); String typeName; try { typeName = ReflectUtil.getSourceName(key.getTypeLiteral()); creationStatements = binding.getCreationStatements(nameGenerator, helperMethodsOutput); } catch (NoSourceNameException e) { errorManager.logError("Error trying to write getter for [%s] -> [%s];" + " binding declaration: %s", e, key, binding, bindingContext); return; } // Name of the field that we might need. String field = nameGenerator.getSingletonFieldName(key); switch (scope) { case EAGER_SINGLETON: initializeEagerSingletonsBody.append("// Eager singleton bound at:\n"); appendBindingContextCommentToMethod(bindingContext, initializeEagerSingletonsBody); initializeEagerSingletonsBody.append(getter).append("();\n"); // !break //CHECKSTYLE_OFF case SINGLETON: //CHECKSTYLE_OFF writer.println("private " + typeName + " " + field + " = null;"); writer.println(); getterBuilder.append(String.format("\nif (%s == null) {\n", field)) .append(creationStatements).append("\n") .append(String.format(" %s = result;\n", field)) .append("}\n") .append(String.format("return %s;\n", field)); break; case NO_SCOPE: sourceWriteUtil.writeBindingContextJavadoc(writer, bindingContext, key); getterBuilder.append(creationStatements).append("\n").append("return result;\n"); break; default: throw new IllegalStateException(); } outputMethod(SourceSnippets.asMethod(false, String.format("public %s %s()", typeName, getter), fragmentPackageName.toString(), getterBuilder.build())); }
[ "void", "writeBindingGetter", "(", "Key", "<", "?", ">", "key", ",", "Binding", "binding", ",", "GinScope", "scope", ",", "List", "<", "InjectorMethod", ">", "helperMethodsOutput", ")", "{", "Context", "bindingContext", "=", "binding", ".", "getContext", "(", ...
Writes a method describing the getter for the given key, along with any other code necessary to support it. Produces a list of helper methods that still need to be written.
[ "Writes", "a", "method", "describing", "the", "getter", "for", "the", "given", "key", "along", "with", "any", "other", "code", "necessary", "to", "support", "it", ".", "Produces", "a", "list", "of", "helper", "methods", "that", "still", "need", "to", "be",...
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/output/GinjectorFragmentOutputter.java#L159-L211
36,977
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/output/GinjectorFragmentOutputter.java
GinjectorFragmentOutputter.commit
void commit() { if (committed) { errorManager.logError("Committed the fragment for %s twice.", fragmentPackageName); return; } committed = true; // Write the field where the enclosing injector is stored. writer.beginJavaDocComment(); writer.print("Field for the enclosing injector."); writer.endJavaDocComment(); writer.println("private final %s injector;", ginjectorClassName); // Write the constructor, which takes the enclosing injector and does // nothing but store it in a field. It's important that the constructor has // no other side-effects; in particular, it must not call any injector // methods, since the injector might not be fully constructed. sourceWriteUtil.writeMethod(writer, String.format("public %s(%s injector)", fragmentClassName, ginjectorClassName), "this.injector = injector;"); if (hasEagerSingletonInitialization()) { // Write a method to initialize eager singletons. sourceWriteUtil.writeMethod( writer, "public void initializeEagerSingletons()", initializeEagerSingletonsBody.toString()); } if (hasStaticInjectionInitialization()) { // Write a method to initialize static injection. sourceWriteUtil.writeMethod( writer, "public void initializeStaticInjections()", initializeStaticInjectionsBody.toString()); } writer.commit(logger); }
java
void commit() { if (committed) { errorManager.logError("Committed the fragment for %s twice.", fragmentPackageName); return; } committed = true; // Write the field where the enclosing injector is stored. writer.beginJavaDocComment(); writer.print("Field for the enclosing injector."); writer.endJavaDocComment(); writer.println("private final %s injector;", ginjectorClassName); // Write the constructor, which takes the enclosing injector and does // nothing but store it in a field. It's important that the constructor has // no other side-effects; in particular, it must not call any injector // methods, since the injector might not be fully constructed. sourceWriteUtil.writeMethod(writer, String.format("public %s(%s injector)", fragmentClassName, ginjectorClassName), "this.injector = injector;"); if (hasEagerSingletonInitialization()) { // Write a method to initialize eager singletons. sourceWriteUtil.writeMethod( writer, "public void initializeEagerSingletons()", initializeEagerSingletonsBody.toString()); } if (hasStaticInjectionInitialization()) { // Write a method to initialize static injection. sourceWriteUtil.writeMethod( writer, "public void initializeStaticInjections()", initializeStaticInjectionsBody.toString()); } writer.commit(logger); }
[ "void", "commit", "(", ")", "{", "if", "(", "committed", ")", "{", "errorManager", ".", "logError", "(", "\"Committed the fragment for %s twice.\"", ",", "fragmentPackageName", ")", ";", "return", ";", "}", "committed", "=", "true", ";", "// Write the field where ...
Outputs all the top-level methods and fields of the class, and commits the writer. Must be the last method invoked on this object.
[ "Outputs", "all", "the", "top", "-", "level", "methods", "and", "fields", "of", "the", "class", "and", "commits", "the", "writer", ".", "Must", "be", "the", "last", "method", "invoked", "on", "this", "object", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/output/GinjectorFragmentOutputter.java#L232-L271
36,978
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/BindingsProcessor.java
BindingsProcessor.registerGinjectorBinding
private void registerGinjectorBinding() { Key<? extends Ginjector> ginjectorKey = Key.get(ginjectorInterface); rootGinjectorBindings.addBinding(ginjectorKey, bindingFactory.getGinjectorBinding()); }
java
private void registerGinjectorBinding() { Key<? extends Ginjector> ginjectorKey = Key.get(ginjectorInterface); rootGinjectorBindings.addBinding(ginjectorKey, bindingFactory.getGinjectorBinding()); }
[ "private", "void", "registerGinjectorBinding", "(", ")", "{", "Key", "<", "?", "extends", "Ginjector", ">", "ginjectorKey", "=", "Key", ".", "get", "(", "ginjectorInterface", ")", ";", "rootGinjectorBindings", ".", "addBinding", "(", "ginjectorKey", ",", "bindin...
Create an explicit binding for the Ginjector.
[ "Create", "an", "explicit", "binding", "for", "the", "Ginjector", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/BindingsProcessor.java#L115-L118
36,979
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/BindingsProcessor.java
BindingsProcessor.resolveAllUnresolvedBindings
private void resolveAllUnresolvedBindings(GinjectorBindings collection) throws UnableToCompleteException { // Create known/explicit bindings before descending into children. This ensures that they are // available to any children that may need to depend on them. createBindingsForFactories(collection); // Visit all children and resolve bindings as appropriate. This visitation may add implicit // bindings (and dependencies) to this ginjector for (GinjectorBindings child : collection.getChildren()) { resolveAllUnresolvedBindings(child); } // Resolve bindings within this ginjector and validate that everything looks OK. collection.resolveBindings(); }
java
private void resolveAllUnresolvedBindings(GinjectorBindings collection) throws UnableToCompleteException { // Create known/explicit bindings before descending into children. This ensures that they are // available to any children that may need to depend on them. createBindingsForFactories(collection); // Visit all children and resolve bindings as appropriate. This visitation may add implicit // bindings (and dependencies) to this ginjector for (GinjectorBindings child : collection.getChildren()) { resolveAllUnresolvedBindings(child); } // Resolve bindings within this ginjector and validate that everything looks OK. collection.resolveBindings(); }
[ "private", "void", "resolveAllUnresolvedBindings", "(", "GinjectorBindings", "collection", ")", "throws", "UnableToCompleteException", "{", "// Create known/explicit bindings before descending into children. This ensures that they are", "// available to any children that may need to depend on...
Create bindings for factories and resolve all implicit bindings for all unresolved bindings in the each injector. <p> This performs a depth-first iteration over all the nodes, and fills in the bindings on the way up the tree. This order is important because creating implicit bindings in a child {@link GinjectorBindings} may add dependencies to the parent. By processing on the way up, we ensure that we only need to process each set once. @param collection {@link GinjectorBindings} to resolve bindings for @throws UnableToCompleteException if binding failed
[ "Create", "bindings", "for", "factories", "and", "resolve", "all", "implicit", "bindings", "for", "all", "unresolved", "bindings", "in", "the", "each", "injector", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/BindingsProcessor.java#L133-L147
36,980
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java
SourceWriteUtil.createFieldInjection
public SourceSnippet createFieldInjection(final FieldLiteral<?> field, final String injecteeName, NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { final boolean hasInjectee = injecteeName != null; final boolean useNativeMethod = field.isPrivate() || ReflectUtil.isPrivate(field.getDeclaringType()) || field.isLegacyFinalField(); // Determine method signature parts. final String injecteeTypeName = ReflectUtil.getSourceName(field.getRawDeclaringType()); String fieldTypeName = ReflectUtil.getSourceName(field.getFieldType()); String methodBaseName = nameGenerator.convertToValidMemberName(injecteeTypeName + "_" + field.getName() + "_fieldInjection"); final String methodName = nameGenerator.createMethodName(methodBaseName); // Field injections are performed in the package of the class declaring the // field. Any private types referenced by the injection must be visible // from there. final String packageName = ReflectUtil.getUserPackageName(field.getDeclaringType()); String signatureParams = fieldTypeName + " value"; boolean isLongAcccess = field.getFieldType().getRawType().equals(Long.TYPE); if (hasInjectee) { signatureParams = injecteeTypeName + " injectee, " + signatureParams; } // Compose method implementation and invocation. String annotation; if (isLongAcccess) { annotation = "@com.google.gwt.core.client.UnsafeNativeLong "; } else { annotation = ""; } String header = useNativeMethod ? "public native " : "public "; String signature = annotation + header + "void " + methodName + "(" + signatureParams + ")"; InjectorMethod injectionMethod = new AbstractInjectorMethod(useNativeMethod, signature, packageName) { public String getMethodBody(InjectorWriteContext writeContext) throws NoSourceNameException { if (!useNativeMethod) { return (hasInjectee ? "injectee." : injecteeTypeName + ".") + field.getName() + " = value;"; } else { return (hasInjectee ? "injectee." : "") + getJsniSignature(field) + " = value;"; } } }; methodsOutput.add(injectionMethod); return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { List<String> callParams = new ArrayList<String>(); if (hasInjectee) { callParams.add(injecteeName); } callParams.add(writeContext.callGetter(guiceUtil.getKey(field))); return writeContext.callMethod(methodName, packageName, callParams) + ";\n"; } }; }
java
public SourceSnippet createFieldInjection(final FieldLiteral<?> field, final String injecteeName, NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { final boolean hasInjectee = injecteeName != null; final boolean useNativeMethod = field.isPrivate() || ReflectUtil.isPrivate(field.getDeclaringType()) || field.isLegacyFinalField(); // Determine method signature parts. final String injecteeTypeName = ReflectUtil.getSourceName(field.getRawDeclaringType()); String fieldTypeName = ReflectUtil.getSourceName(field.getFieldType()); String methodBaseName = nameGenerator.convertToValidMemberName(injecteeTypeName + "_" + field.getName() + "_fieldInjection"); final String methodName = nameGenerator.createMethodName(methodBaseName); // Field injections are performed in the package of the class declaring the // field. Any private types referenced by the injection must be visible // from there. final String packageName = ReflectUtil.getUserPackageName(field.getDeclaringType()); String signatureParams = fieldTypeName + " value"; boolean isLongAcccess = field.getFieldType().getRawType().equals(Long.TYPE); if (hasInjectee) { signatureParams = injecteeTypeName + " injectee, " + signatureParams; } // Compose method implementation and invocation. String annotation; if (isLongAcccess) { annotation = "@com.google.gwt.core.client.UnsafeNativeLong "; } else { annotation = ""; } String header = useNativeMethod ? "public native " : "public "; String signature = annotation + header + "void " + methodName + "(" + signatureParams + ")"; InjectorMethod injectionMethod = new AbstractInjectorMethod(useNativeMethod, signature, packageName) { public String getMethodBody(InjectorWriteContext writeContext) throws NoSourceNameException { if (!useNativeMethod) { return (hasInjectee ? "injectee." : injecteeTypeName + ".") + field.getName() + " = value;"; } else { return (hasInjectee ? "injectee." : "") + getJsniSignature(field) + " = value;"; } } }; methodsOutput.add(injectionMethod); return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { List<String> callParams = new ArrayList<String>(); if (hasInjectee) { callParams.add(injecteeName); } callParams.add(writeContext.callGetter(guiceUtil.getKey(field))); return writeContext.callMethod(methodName, packageName, callParams) + ";\n"; } }; }
[ "public", "SourceSnippet", "createFieldInjection", "(", "final", "FieldLiteral", "<", "?", ">", "field", ",", "final", "String", "injecteeName", ",", "NameGenerator", "nameGenerator", ",", "List", "<", "InjectorMethod", ">", "methodsOutput", ")", "throws", "NoSource...
Creates a field injecting method and returns a string that invokes the written method. @param field field to be injected @param injecteeName variable that references the object into which values are injected, in the context of the returned call string @param nameGenerator NameGenerator to be used for ensuring method name uniqueness @return string calling the generated method
[ "Creates", "a", "field", "injecting", "method", "and", "returns", "a", "string", "that", "invokes", "the", "written", "method", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java#L93-L155
36,981
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java
SourceWriteUtil.writeBindingContext
public void writeBindingContext(SourceWriter writer, Context context) { // Avoid a trailing \n -- the GWT class source file composer will output an // ugly extra newline if we do that. String text = context.toString(); boolean first = true; for (String line : text.split("\n")) { if (first) { first = false; } else { writer.println(); } // Indent the line relative to its current location. writer.indent() // won't work, since it does the wrong thing in Javadoc. writer.print(" "); writer.print(line); } }
java
public void writeBindingContext(SourceWriter writer, Context context) { // Avoid a trailing \n -- the GWT class source file composer will output an // ugly extra newline if we do that. String text = context.toString(); boolean first = true; for (String line : text.split("\n")) { if (first) { first = false; } else { writer.println(); } // Indent the line relative to its current location. writer.indent() // won't work, since it does the wrong thing in Javadoc. writer.print(" "); writer.print(line); } }
[ "public", "void", "writeBindingContext", "(", "SourceWriter", "writer", ",", "Context", "context", ")", "{", "// Avoid a trailing \\n -- the GWT class source file composer will output an", "// ugly extra newline if we do that.", "String", "text", "=", "context", ".", "toString", ...
Writes out a binding context, followed by a newline. <p>Binding contexts may contain newlines; this routine translates those for the SourceWriter to ensure that indents, Javadoc comments, etc are handled properly.
[ "Writes", "out", "a", "binding", "context", "followed", "by", "a", "newline", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java#L205-L221
36,982
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java
SourceWriteUtil.writeBindingContextJavadoc
public void writeBindingContextJavadoc(SourceWriter writer, Context bindingContext, String description) { writer.beginJavaDocComment(); writer.println(description); writeBindingContext(writer, bindingContext); writer.endJavaDocComment(); }
java
public void writeBindingContextJavadoc(SourceWriter writer, Context bindingContext, String description) { writer.beginJavaDocComment(); writer.println(description); writeBindingContext(writer, bindingContext); writer.endJavaDocComment(); }
[ "public", "void", "writeBindingContextJavadoc", "(", "SourceWriter", "writer", ",", "Context", "bindingContext", ",", "String", "description", ")", "{", "writer", ".", "beginJavaDocComment", "(", ")", ";", "writer", ".", "println", "(", "description", ")", ";", ...
Write a Javadoc comment for a binding, including its context. @param description The description of the binding printed before its location, such as "Foo bound at: " @param writer The writer to use in displaying the context. @param bindingContext The context of the binding.
[ "Write", "a", "Javadoc", "comment", "for", "a", "binding", "including", "its", "context", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java#L231-L237
36,983
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java
SourceWriteUtil.writeBindingContextJavadoc
public void writeBindingContextJavadoc(SourceWriter writer, Context bindingContext, Key<?> key) { writeBindingContextJavadoc(writer, bindingContext, "Binding for " + key.getTypeLiteral() + " declared at:"); }
java
public void writeBindingContextJavadoc(SourceWriter writer, Context bindingContext, Key<?> key) { writeBindingContextJavadoc(writer, bindingContext, "Binding for " + key.getTypeLiteral() + " declared at:"); }
[ "public", "void", "writeBindingContextJavadoc", "(", "SourceWriter", "writer", ",", "Context", "bindingContext", ",", "Key", "<", "?", ">", "key", ")", "{", "writeBindingContextJavadoc", "(", "writer", ",", "bindingContext", ",", "\"Binding for \"", "+", "key", "....
Write the Javadoc for the binding of a particular key, showing the context of the binding. @param key The bound key. @param writer The writer to use to write this comment. @param bindingContext The context of the binding.
[ "Write", "the", "Javadoc", "for", "the", "binding", "of", "a", "particular", "key", "showing", "the", "context", "of", "the", "binding", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java#L247-L251
36,984
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java
SourceWriteUtil.writeMethod
public void writeMethod(SourceWriter writer, String signature, String body) { writer.println(signature + " {"); writer.indent(); writer.println(body); writer.outdent(); writer.println("}"); writer.println(); }
java
public void writeMethod(SourceWriter writer, String signature, String body) { writer.println(signature + " {"); writer.indent(); writer.println(body); writer.outdent(); writer.println("}"); writer.println(); }
[ "public", "void", "writeMethod", "(", "SourceWriter", "writer", ",", "String", "signature", ",", "String", "body", ")", "{", "writer", ".", "println", "(", "signature", "+", "\" {\"", ")", ";", "writer", ".", "indent", "(", ")", ";", "writer", ".", "prin...
Writes a method with the given signature and body to the source writer. @param writer writer that the method is written to @param signature method's signature @param body method's body
[ "Writes", "a", "method", "with", "the", "given", "signature", "and", "body", "to", "the", "source", "writer", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java#L260-L267
36,985
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java
SourceWriteUtil.writeMethod
public void writeMethod(InjectorMethod method, SourceWriter writer, InjectorWriteContext writeContext) throws NoSourceNameException { if (method.isNative()) { writeNativeMethod(writer, method.getMethodSignature(), method.getMethodBody(writeContext)); } else { writeMethod(writer, method.getMethodSignature(), method.getMethodBody(writeContext)); } }
java
public void writeMethod(InjectorMethod method, SourceWriter writer, InjectorWriteContext writeContext) throws NoSourceNameException { if (method.isNative()) { writeNativeMethod(writer, method.getMethodSignature(), method.getMethodBody(writeContext)); } else { writeMethod(writer, method.getMethodSignature(), method.getMethodBody(writeContext)); } }
[ "public", "void", "writeMethod", "(", "InjectorMethod", "method", ",", "SourceWriter", "writer", ",", "InjectorWriteContext", "writeContext", ")", "throws", "NoSourceNameException", "{", "if", "(", "method", ".", "isNative", "(", ")", ")", "{", "writeNativeMethod", ...
Writes the given method to the given source writer.
[ "Writes", "the", "given", "method", "to", "the", "given", "source", "writer", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java#L289-L296
36,986
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java
SourceWriteUtil.writeMethods
public void writeMethods(Iterable<InjectorMethod> methods, SourceWriter writer, InjectorWriteContext writeContext) throws NoSourceNameException { for (InjectorMethod method : methods) { writeMethod(method, writer, writeContext); } }
java
public void writeMethods(Iterable<InjectorMethod> methods, SourceWriter writer, InjectorWriteContext writeContext) throws NoSourceNameException { for (InjectorMethod method : methods) { writeMethod(method, writer, writeContext); } }
[ "public", "void", "writeMethods", "(", "Iterable", "<", "InjectorMethod", ">", "methods", ",", "SourceWriter", "writer", ",", "InjectorWriteContext", "writeContext", ")", "throws", "NoSourceNameException", "{", "for", "(", "InjectorMethod", "method", ":", "methods", ...
Writes the given methods to the given source writer. @param methods the methods to write @param writer the source writer to which the methods should be written @param writeContext the context in which to write the methods
[ "Writes", "the", "given", "methods", "to", "the", "given", "source", "writer", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java#L305-L310
36,987
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java
SourceWriteUtil.createMemberInjection
public String createMemberInjection(TypeLiteral<?> type, NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { String memberInjectMethodName = nameGenerator.getMemberInjectMethodName(type); String memberInjectMethodSignature = "public void " + memberInjectMethodName + "(" + ReflectUtil.getSourceName(type) + " injectee)"; SourceSnippetBuilder sb = new SourceSnippetBuilder(); sb.append(createFieldInjections(getFieldsToInject(type), "injectee", nameGenerator, methodsOutput)); sb.append(createMethodInjections(getMethodsToInject(type), "injectee", nameGenerator, methodsOutput)); // Generate the top-level member inject method in the package containing the // type we're injecting: methodsOutput.add(SourceSnippets.asMethod(false, memberInjectMethodSignature, ReflectUtil.getUserPackageName(type), sb.build())); return memberInjectMethodName; }
java
public String createMemberInjection(TypeLiteral<?> type, NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { String memberInjectMethodName = nameGenerator.getMemberInjectMethodName(type); String memberInjectMethodSignature = "public void " + memberInjectMethodName + "(" + ReflectUtil.getSourceName(type) + " injectee)"; SourceSnippetBuilder sb = new SourceSnippetBuilder(); sb.append(createFieldInjections(getFieldsToInject(type), "injectee", nameGenerator, methodsOutput)); sb.append(createMethodInjections(getMethodsToInject(type), "injectee", nameGenerator, methodsOutput)); // Generate the top-level member inject method in the package containing the // type we're injecting: methodsOutput.add(SourceSnippets.asMethod(false, memberInjectMethodSignature, ReflectUtil.getUserPackageName(type), sb.build())); return memberInjectMethodName; }
[ "public", "String", "createMemberInjection", "(", "TypeLiteral", "<", "?", ">", "type", ",", "NameGenerator", "nameGenerator", ",", "List", "<", "InjectorMethod", ">", "methodsOutput", ")", "throws", "NoSourceNameException", "{", "String", "memberInjectMethodName", "=...
Generates all the required injector methods to inject members of the given type, and a standard member-inject method that invokes them. @param type type for which the injection is performed @param nameGenerator the name generator used to create method names @param methodsOutput a list to which the new injection method and all its helpers are added @return name of the method created
[ "Generates", "all", "the", "required", "injector", "methods", "to", "inject", "members", "of", "the", "given", "type", "and", "a", "standard", "member", "-", "inject", "method", "that", "invokes", "them", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/SourceWriteUtil.java#L322-L341
36,988
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/MethodCallUtil.java
MethodCallUtil.createConstructorInjection
public SourceSnippet createConstructorInjection( MethodLiteral<?, Constructor<?>> constructor, NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { return createMethodCallWithInjection(constructor, null, nameGenerator, methodsOutput); }
java
public SourceSnippet createConstructorInjection( MethodLiteral<?, Constructor<?>> constructor, NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { return createMethodCallWithInjection(constructor, null, nameGenerator, methodsOutput); }
[ "public", "SourceSnippet", "createConstructorInjection", "(", "MethodLiteral", "<", "?", ",", "Constructor", "<", "?", ">", ">", "constructor", ",", "NameGenerator", "nameGenerator", ",", "List", "<", "InjectorMethod", ">", "methodsOutput", ")", "throws", "NoSourceN...
Creates a constructor injecting method and returns a string that invokes the new method. The new method returns the constructed object. @param constructor constructor to call @param nameGenerator NameGenerator to be used for ensuring method name uniqueness @param methodsOutput a list where all new methods created by this call are added @return source snippet calling the generated method
[ "Creates", "a", "constructor", "injecting", "method", "and", "returns", "a", "string", "that", "invokes", "the", "new", "method", ".", "The", "new", "method", "returns", "the", "constructed", "object", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/MethodCallUtil.java#L52-L56
36,989
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/MethodCallUtil.java
MethodCallUtil.createMethodCallWithInjection
public SourceSnippet createMethodCallWithInjection(MethodLiteral<?, ?> method, String invokeeName, NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { String[] params = new String[method.getParameterTypes().size()]; return createMethodCallWithInjection(method, invokeeName, params, nameGenerator, methodsOutput); }
java
public SourceSnippet createMethodCallWithInjection(MethodLiteral<?, ?> method, String invokeeName, NameGenerator nameGenerator, List<InjectorMethod> methodsOutput) throws NoSourceNameException { String[] params = new String[method.getParameterTypes().size()]; return createMethodCallWithInjection(method, invokeeName, params, nameGenerator, methodsOutput); }
[ "public", "SourceSnippet", "createMethodCallWithInjection", "(", "MethodLiteral", "<", "?", ",", "?", ">", "method", ",", "String", "invokeeName", ",", "NameGenerator", "nameGenerator", ",", "List", "<", "InjectorMethod", ">", "methodsOutput", ")", "throws", "NoSour...
Creates a method that calls the passed method, injecting its parameters using getters, and returns a string that invokes the new method. The new method returns the passed method's return value, if any. If a method without parameters is provided, that method will be called and no parameters will be passed. @param method method to call (can be constructor) @param invokeeName expression that evaluates to the object on which the method is to be called. If null the method will be called in the current scope. @param nameGenerator NameGenerator to be used for ensuring method name uniqueness @param methodsOutput a list where all new methods created by this call are added @return source snippet calling the generated method
[ "Creates", "a", "method", "that", "calls", "the", "passed", "method", "injecting", "its", "parameters", "using", "getters", "and", "returns", "a", "string", "that", "invokes", "the", "new", "method", ".", "The", "new", "method", "returns", "the", "passed", "...
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/MethodCallUtil.java#L74-L80
36,990
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/MethodCallUtil.java
MethodCallUtil.isLongAccess
private boolean isLongAccess(MethodLiteral<?, ?> method) { boolean result = method.getReturnType().getRawType().equals(Long.TYPE); for (TypeLiteral<?> paramLiteral : method.getParameterTypes()) { result |= paramLiteral.getRawType().equals(Long.TYPE); } return result; }
java
private boolean isLongAccess(MethodLiteral<?, ?> method) { boolean result = method.getReturnType().getRawType().equals(Long.TYPE); for (TypeLiteral<?> paramLiteral : method.getParameterTypes()) { result |= paramLiteral.getRawType().equals(Long.TYPE); } return result; }
[ "private", "boolean", "isLongAccess", "(", "MethodLiteral", "<", "?", ",", "?", ">", "method", ")", "{", "boolean", "result", "=", "method", ".", "getReturnType", "(", ")", ".", "getRawType", "(", ")", ".", "equals", "(", "Long", ".", "TYPE", ")", ";",...
Check whether a method needs to have Long access.
[ "Check", "whether", "a", "method", "needs", "to", "have", "Long", "access", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/MethodCallUtil.java#L156-L163
36,991
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/GinBridgeClassLoader.java
GinBridgeClassLoader.findClass
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (!loadedClassFiles) { classFileMap = extractClassFileMap(); loadedClassFiles = true; } if (classFileMap == null) { throw new ClassNotFoundException(name); } String internalName = name.replace('.', '/'); CompiledClass compiledClass = classFileMap.get(internalName); if (compiledClass == null) { throw new ClassNotFoundException(name); } // Make sure the class's package is present. String pkg = compiledClass.getPackageName(); if (getPackage(pkg) == null) { definePackage(pkg, null, null, null, null, null, null, null); } byte[] bytes = compiledClass.getBytes(); return defineClass(name, bytes, 0, bytes.length); }
java
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (!loadedClassFiles) { classFileMap = extractClassFileMap(); loadedClassFiles = true; } if (classFileMap == null) { throw new ClassNotFoundException(name); } String internalName = name.replace('.', '/'); CompiledClass compiledClass = classFileMap.get(internalName); if (compiledClass == null) { throw new ClassNotFoundException(name); } // Make sure the class's package is present. String pkg = compiledClass.getPackageName(); if (getPackage(pkg) == null) { definePackage(pkg, null, null, null, null, null, null, null); } byte[] bytes = compiledClass.getBytes(); return defineClass(name, bytes, 0, bytes.length); }
[ "@", "Override", "protected", "Class", "<", "?", ">", "findClass", "(", "String", "name", ")", "throws", "ClassNotFoundException", "{", "if", "(", "!", "loadedClassFiles", ")", "{", "classFileMap", "=", "extractClassFileMap", "(", ")", ";", "loadedClassFiles", ...
Looks up classes in GWT's compilation state.
[ "Looks", "up", "classes", "in", "GWT", "s", "compilation", "state", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/GinBridgeClassLoader.java#L135-L160
36,992
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/resolution/ImplicitBindingCreator.java
ImplicitBindingCreator.create
public Binding create(Key<?> key) throws BindingCreationException { TypeLiteral<?> type = key.getTypeLiteral(); // All steps per: // http://code.google.com/p/google-guice/wiki/BindingResolution // 1. Explicit binding - already finished at this point. // 2. Ask parent injector. // 3. Ask child injector. // These bindings are created in BindingResolver and are not necessary here. // 4. Provider injections. if (isProviderKey(key)) { return bindingFactory.getImplicitProviderBinding(key); // TODO(bstoler): Scope the provider binding like the thing being provided? } // 4b. AsyncProvider injections. if (isAsyncProviderKey(key)) { return bindingFactory.getAsyncProviderBinding(key); } // 5. Convert constants. // Already covered by resolving explicit bindings. if (BindConstantBinding.isConstantKey(key)) { throw new BindingCreationException( "Binding requested for constant key '%s' but no explicit binding was found", key); } // 6. If the dependency has a binding annotation, give up. if (key.getAnnotation() != null || key.getAnnotationType() != null) { throw new BindingCreationException("No implementation bound for '%s' and an implicit binding" + " cannot be created because the type is annotated.", key); } // 7. If the dependency is an array or enum, give up. // Covered by step 5 (enum) and 11 (array). // 8. Handle TypeLiteral injections. // TODO(schmitt): Implement TypeLiteral injections. // 9. Use resolution annotations (@ImplementedBy, @ProvidedBy) ImplementedBy implementedBy = type.getRawType().getAnnotation(ImplementedBy.class); if (implementedBy != null) { return createImplementedByBinding(key, implementedBy); } ProvidedBy providedBy = type.getRawType().getAnnotation(ProvidedBy.class); if (providedBy != null) { return createProvidedByBinding(key, providedBy); } // 10. If the dependency is abstract or a non-static inner class, give up. // Abstract classes are handled by GWT.create. // TODO(schmitt): Introduce check. // 11. Use a single @Inject or public no-arguments constructor. return createImplicitBindingForClass(type); }
java
public Binding create(Key<?> key) throws BindingCreationException { TypeLiteral<?> type = key.getTypeLiteral(); // All steps per: // http://code.google.com/p/google-guice/wiki/BindingResolution // 1. Explicit binding - already finished at this point. // 2. Ask parent injector. // 3. Ask child injector. // These bindings are created in BindingResolver and are not necessary here. // 4. Provider injections. if (isProviderKey(key)) { return bindingFactory.getImplicitProviderBinding(key); // TODO(bstoler): Scope the provider binding like the thing being provided? } // 4b. AsyncProvider injections. if (isAsyncProviderKey(key)) { return bindingFactory.getAsyncProviderBinding(key); } // 5. Convert constants. // Already covered by resolving explicit bindings. if (BindConstantBinding.isConstantKey(key)) { throw new BindingCreationException( "Binding requested for constant key '%s' but no explicit binding was found", key); } // 6. If the dependency has a binding annotation, give up. if (key.getAnnotation() != null || key.getAnnotationType() != null) { throw new BindingCreationException("No implementation bound for '%s' and an implicit binding" + " cannot be created because the type is annotated.", key); } // 7. If the dependency is an array or enum, give up. // Covered by step 5 (enum) and 11 (array). // 8. Handle TypeLiteral injections. // TODO(schmitt): Implement TypeLiteral injections. // 9. Use resolution annotations (@ImplementedBy, @ProvidedBy) ImplementedBy implementedBy = type.getRawType().getAnnotation(ImplementedBy.class); if (implementedBy != null) { return createImplementedByBinding(key, implementedBy); } ProvidedBy providedBy = type.getRawType().getAnnotation(ProvidedBy.class); if (providedBy != null) { return createProvidedByBinding(key, providedBy); } // 10. If the dependency is abstract or a non-static inner class, give up. // Abstract classes are handled by GWT.create. // TODO(schmitt): Introduce check. // 11. Use a single @Inject or public no-arguments constructor. return createImplicitBindingForClass(type); }
[ "public", "Binding", "create", "(", "Key", "<", "?", ">", "key", ")", "throws", "BindingCreationException", "{", "TypeLiteral", "<", "?", ">", "type", "=", "key", ".", "getTypeLiteral", "(", ")", ";", "// All steps per:", "// http://code.google.com/p/google-guice/...
Creates the implicit binding.
[ "Creates", "the", "implicit", "binding", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/resolution/ImplicitBindingCreator.java#L82-L141
36,993
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/output/ReachabilityAnalyzer.java
ReachabilityAnalyzer.traceGinjectorMethods
private void traceGinjectorMethods() { TypeLiteral<?> ginjectorInterface = rootBindings.getGinjectorInterface(); for (MethodLiteral<?, Method> method : memberCollector.getMethods(ginjectorInterface)) { if (!guiceUtil.isMemberInject(method)) { // It's a constructor method, so just trace to the key that's // constructed. Key<?> key = guiceUtil.getKey(method); PrettyPrinter.log(logger, TreeLogger.DEBUG, "ROOT -> %s:%s [%s]", rootBindings, key, method); traceKey(key, rootBindings); } else { Key<?> sourceKey = guiceUtil.getKey(method); getReachableMemberInjects(rootBindings).add(sourceKey.getTypeLiteral()); for (Dependency dependency : guiceUtil.getMemberInjectionDependencies(sourceKey, sourceKey.getTypeLiteral())) { Key<?> targetKey = dependency.getTarget(); PrettyPrinter.log( logger, TreeLogger.DEBUG, "ROOT -> %s:%s [%s]", rootBindings, targetKey, method); traceKey(targetKey, rootBindings); } } } }
java
private void traceGinjectorMethods() { TypeLiteral<?> ginjectorInterface = rootBindings.getGinjectorInterface(); for (MethodLiteral<?, Method> method : memberCollector.getMethods(ginjectorInterface)) { if (!guiceUtil.isMemberInject(method)) { // It's a constructor method, so just trace to the key that's // constructed. Key<?> key = guiceUtil.getKey(method); PrettyPrinter.log(logger, TreeLogger.DEBUG, "ROOT -> %s:%s [%s]", rootBindings, key, method); traceKey(key, rootBindings); } else { Key<?> sourceKey = guiceUtil.getKey(method); getReachableMemberInjects(rootBindings).add(sourceKey.getTypeLiteral()); for (Dependency dependency : guiceUtil.getMemberInjectionDependencies(sourceKey, sourceKey.getTypeLiteral())) { Key<?> targetKey = dependency.getTarget(); PrettyPrinter.log( logger, TreeLogger.DEBUG, "ROOT -> %s:%s [%s]", rootBindings, targetKey, method); traceKey(targetKey, rootBindings); } } } }
[ "private", "void", "traceGinjectorMethods", "(", ")", "{", "TypeLiteral", "<", "?", ">", "ginjectorInterface", "=", "rootBindings", ".", "getGinjectorInterface", "(", ")", ";", "for", "(", "MethodLiteral", "<", "?", ",", "Method", ">", "method", ":", "memberCo...
Traces out bindings that are reachable from a GInjector method.
[ "Traces", "out", "bindings", "that", "are", "reachable", "from", "a", "GInjector", "method", "." ]
595e61ee0d2fa508815c016e924ec0e5cea2a2aa
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/output/ReachabilityAnalyzer.java#L138-L163
36,994
skyscreamer/yoga
yoga-core/src/main/java/org/skyscreamer/yoga/metadata/DefaultMetaDataRegistry.java
DefaultMetaDataRegistry.getNameForType
private String getNameForType( Class<?> type ) { if ( _typeToStringMap.containsKey( type ) ) { return _typeToStringMap.get( type ); } for ( Entry<String, Class<?>> entry : _typeMappings.entrySet() ) { if ( entry.getValue().isAssignableFrom( type ) ) { return entry.getKey(); } } return null; }
java
private String getNameForType( Class<?> type ) { if ( _typeToStringMap.containsKey( type ) ) { return _typeToStringMap.get( type ); } for ( Entry<String, Class<?>> entry : _typeMappings.entrySet() ) { if ( entry.getValue().isAssignableFrom( type ) ) { return entry.getKey(); } } return null; }
[ "private", "String", "getNameForType", "(", "Class", "<", "?", ">", "type", ")", "{", "if", "(", "_typeToStringMap", ".", "containsKey", "(", "type", ")", ")", "{", "return", "_typeToStringMap", ".", "get", "(", "type", ")", ";", "}", "for", "(", "Entr...
given a type, get a name. This takes subclassing into consideration. For now, this will return the first subclass match to the type, not the closest
[ "given", "a", "type", "get", "a", "name", ".", "This", "takes", "subclassing", "into", "consideration", ".", "For", "now", "this", "will", "return", "the", "first", "subclass", "match", "to", "the", "type", "not", "the", "closest" ]
d98f6b0b2b60ff195cc6878ed54e515e639bc9da
https://github.com/skyscreamer/yoga/blob/d98f6b0b2b60ff195cc6878ed54e515e639bc9da/yoga-core/src/main/java/org/skyscreamer/yoga/metadata/DefaultMetaDataRegistry.java#L86-L101
36,995
hpsa/hpe-application-automation-tools-plugin
src/main/java/com/hp/application/automation/tools/rest/RestClient.java
RestClient.setProxyCfg
public static ProxyInfo setProxyCfg(String host, String port, String userName, String password) { return new ProxyInfo(host, port, userName, password); }
java
public static ProxyInfo setProxyCfg(String host, String port, String userName, String password) { return new ProxyInfo(host, port, userName, password); }
[ "public", "static", "ProxyInfo", "setProxyCfg", "(", "String", "host", ",", "String", "port", ",", "String", "userName", ",", "String", "password", ")", "{", "return", "new", "ProxyInfo", "(", "host", ",", "port", ",", "userName", ",", "password", ")", ";"...
Set proxy configuration. @param host @param port @param userName @param password @return proxyinfo instance
[ "Set", "proxy", "configuration", "." ]
987536f5551bc76fd028d746a951d1fd72c7567a
https://github.com/hpsa/hpe-application-automation-tools-plugin/blob/987536f5551bc76fd028d746a951d1fd72c7567a/src/main/java/com/hp/application/automation/tools/rest/RestClient.java#L422-L424
36,996
hpsa/hpe-application-automation-tools-plugin
src/main/java/com/hp/application/automation/tools/results/RunResultRecorder.java
RunResultRecorder.createHtmlReport
@SuppressWarnings("squid:S134") private void createHtmlReport(FilePath reportFolder, String testFolderPath, File artifactsDir, List<String> reportNames, TestResult testResult) throws IOException, InterruptedException { String archiveTestResultMode = _resultsPublisherModel.getArchiveTestResultsMode(); boolean createReport = archiveTestResultMode.equals(ResultsPublisherModel.CreateHtmlReportResults.getValue()); if (createReport) { File testFolderPathFile = new File(testFolderPath); FilePath srcDirectoryFilePath = new FilePath(reportFolder, HTML_REPORT_FOLDER); if (srcDirectoryFilePath.exists()) { FilePath srcFilePath = new FilePath(srcDirectoryFilePath, IE_REPORT_FOLDER); if (srcFilePath.exists()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); srcFilePath.zip(baos); File reportDirectory = new File(artifactsDir.getParent(), PERFORMANCE_REPORT_FOLDER); if (!reportDirectory.exists()) { reportDirectory.mkdir(); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); FilePath reportDirectoryFilePath = new FilePath(reportDirectory); FilePath tmpZipFile = new FilePath(reportDirectoryFilePath, "tmp.zip"); tmpZipFile.copyFrom(bais); bais.close(); baos.close(); tmpZipFile.unzip(reportDirectoryFilePath); String newFolderName = org.apache.commons.io.FilenameUtils.getName(testFolderPathFile.getPath()); FileUtils.moveDirectory(new File(reportDirectory, IE_REPORT_FOLDER), new File(reportDirectory, newFolderName)); tmpZipFile.delete(); outputReportFiles(reportNames, reportDirectory, testResult, false); } } } }
java
@SuppressWarnings("squid:S134") private void createHtmlReport(FilePath reportFolder, String testFolderPath, File artifactsDir, List<String> reportNames, TestResult testResult) throws IOException, InterruptedException { String archiveTestResultMode = _resultsPublisherModel.getArchiveTestResultsMode(); boolean createReport = archiveTestResultMode.equals(ResultsPublisherModel.CreateHtmlReportResults.getValue()); if (createReport) { File testFolderPathFile = new File(testFolderPath); FilePath srcDirectoryFilePath = new FilePath(reportFolder, HTML_REPORT_FOLDER); if (srcDirectoryFilePath.exists()) { FilePath srcFilePath = new FilePath(srcDirectoryFilePath, IE_REPORT_FOLDER); if (srcFilePath.exists()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); srcFilePath.zip(baos); File reportDirectory = new File(artifactsDir.getParent(), PERFORMANCE_REPORT_FOLDER); if (!reportDirectory.exists()) { reportDirectory.mkdir(); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); FilePath reportDirectoryFilePath = new FilePath(reportDirectory); FilePath tmpZipFile = new FilePath(reportDirectoryFilePath, "tmp.zip"); tmpZipFile.copyFrom(bais); bais.close(); baos.close(); tmpZipFile.unzip(reportDirectoryFilePath); String newFolderName = org.apache.commons.io.FilenameUtils.getName(testFolderPathFile.getPath()); FileUtils.moveDirectory(new File(reportDirectory, IE_REPORT_FOLDER), new File(reportDirectory, newFolderName)); tmpZipFile.delete(); outputReportFiles(reportNames, reportDirectory, testResult, false); } } } }
[ "@", "SuppressWarnings", "(", "\"squid:S134\"", ")", "private", "void", "createHtmlReport", "(", "FilePath", "reportFolder", ",", "String", "testFolderPath", ",", "File", "artifactsDir", ",", "List", "<", "String", ">", "reportNames", ",", "TestResult", "testResult"...
Copy Summary Html reports created by LoadRunner @param reportFolder @param testFolderPath @param artifactsDir @param reportNames @param testResult @throws IOException @throws InterruptedException
[ "Copy", "Summary", "Html", "reports", "created", "by", "LoadRunner" ]
987536f5551bc76fd028d746a951d1fd72c7567a
https://github.com/hpsa/hpe-application-automation-tools-plugin/blob/987536f5551bc76fd028d746a951d1fd72c7567a/src/main/java/com/hp/application/automation/tools/results/RunResultRecorder.java#L749-L787
36,997
hpsa/hpe-application-automation-tools-plugin
src/main/java/com/hp/application/automation/tools/results/RunResultRecorder.java
RunResultRecorder.createTransactionSummary
private void createTransactionSummary(FilePath reportFolder, String testFolderPath, File artifactsDir, List<String> reportNames, TestResult testResult) throws IOException, InterruptedException { File testFolderPathFile = new File(testFolderPath); String subFolder = HTML_REPORT_FOLDER + File.separator + IE_REPORT_FOLDER + File.separator + HTML_REPORT_FOLDER; FilePath htmlReportPath = new FilePath(reportFolder, subFolder); if (htmlReportPath.exists()) { File reportDirectory = new File(artifactsDir.getParent(), TRANSACTION_SUMMARY_FOLDER); if (!reportDirectory.exists()) { reportDirectory.mkdir(); } String newFolderName = org.apache.commons.io.FilenameUtils.getName(testFolderPathFile.getPath()); File testDirectory = new File(reportDirectory, newFolderName); if (!testDirectory.exists()) { testDirectory.mkdir(); } FilePath dstReportPath = new FilePath(testDirectory); FileFilter reportFileFilter = new WildcardFileFilter(TRANSACTION_REPORT_NAME + ".*"); List<FilePath> reporFiles = htmlReportPath.list(reportFileFilter); for (FilePath fileToCopy : reporFiles) { FilePath dstFilePath = new FilePath(dstReportPath, fileToCopy.getName()); fileToCopy.copyTo(dstFilePath); } FilePath cssFilePath = new FilePath(htmlReportPath, "Properties.css"); if (cssFilePath.exists()) { FilePath dstFilePath = new FilePath(dstReportPath, cssFilePath.getName()); cssFilePath.copyTo(dstFilePath); } FilePath pngFilePath = new FilePath(htmlReportPath, "tbic_toexcel.png"); if (pngFilePath.exists()) { FilePath dstFilePath = new FilePath(dstReportPath, pngFilePath.getName()); pngFilePath.copyTo(dstFilePath); } outputReportFiles(reportNames, reportDirectory, testResult, true); } }
java
private void createTransactionSummary(FilePath reportFolder, String testFolderPath, File artifactsDir, List<String> reportNames, TestResult testResult) throws IOException, InterruptedException { File testFolderPathFile = new File(testFolderPath); String subFolder = HTML_REPORT_FOLDER + File.separator + IE_REPORT_FOLDER + File.separator + HTML_REPORT_FOLDER; FilePath htmlReportPath = new FilePath(reportFolder, subFolder); if (htmlReportPath.exists()) { File reportDirectory = new File(artifactsDir.getParent(), TRANSACTION_SUMMARY_FOLDER); if (!reportDirectory.exists()) { reportDirectory.mkdir(); } String newFolderName = org.apache.commons.io.FilenameUtils.getName(testFolderPathFile.getPath()); File testDirectory = new File(reportDirectory, newFolderName); if (!testDirectory.exists()) { testDirectory.mkdir(); } FilePath dstReportPath = new FilePath(testDirectory); FileFilter reportFileFilter = new WildcardFileFilter(TRANSACTION_REPORT_NAME + ".*"); List<FilePath> reporFiles = htmlReportPath.list(reportFileFilter); for (FilePath fileToCopy : reporFiles) { FilePath dstFilePath = new FilePath(dstReportPath, fileToCopy.getName()); fileToCopy.copyTo(dstFilePath); } FilePath cssFilePath = new FilePath(htmlReportPath, "Properties.css"); if (cssFilePath.exists()) { FilePath dstFilePath = new FilePath(dstReportPath, cssFilePath.getName()); cssFilePath.copyTo(dstFilePath); } FilePath pngFilePath = new FilePath(htmlReportPath, "tbic_toexcel.png"); if (pngFilePath.exists()) { FilePath dstFilePath = new FilePath(dstReportPath, pngFilePath.getName()); pngFilePath.copyTo(dstFilePath); } outputReportFiles(reportNames, reportDirectory, testResult, true); } }
[ "private", "void", "createTransactionSummary", "(", "FilePath", "reportFolder", ",", "String", "testFolderPath", ",", "File", "artifactsDir", ",", "List", "<", "String", ">", "reportNames", ",", "TestResult", "testResult", ")", "throws", "IOException", ",", "Interru...
Copies and creates the transaction summery on the master @param reportFolder @param testFolderPath @param artifactsDir @param reportNames @param testResult @throws IOException @throws InterruptedException
[ "Copies", "and", "creates", "the", "transaction", "summery", "on", "the", "master" ]
987536f5551bc76fd028d746a951d1fd72c7567a
https://github.com/hpsa/hpe-application-automation-tools-plugin/blob/987536f5551bc76fd028d746a951d1fd72c7567a/src/main/java/com/hp/application/automation/tools/results/RunResultRecorder.java#L909-L951
36,998
hpsa/hpe-application-automation-tools-plugin
src/main/java/com/hp/application/automation/tools/run/SseBuilder.java
SseBuilder.setProxyCredentials
private void setProxyCredentials(Run<?, ?> run) { if (proxySettings != null && proxySettings.getFsProxyCredentialsId() != null) { UsernamePasswordCredentials up = CredentialsProvider.findCredentialById( proxySettings.getFsProxyCredentialsId(), StandardUsernamePasswordCredentials.class, run, URIRequirementBuilder.create().build()); if (up != null) { proxySettings.setFsProxyUserName(up.getUsername()); proxySettings.setFsProxyPassword(up.getPassword()); } } }
java
private void setProxyCredentials(Run<?, ?> run) { if (proxySettings != null && proxySettings.getFsProxyCredentialsId() != null) { UsernamePasswordCredentials up = CredentialsProvider.findCredentialById( proxySettings.getFsProxyCredentialsId(), StandardUsernamePasswordCredentials.class, run, URIRequirementBuilder.create().build()); if (up != null) { proxySettings.setFsProxyUserName(up.getUsername()); proxySettings.setFsProxyPassword(up.getPassword()); } } }
[ "private", "void", "setProxyCredentials", "(", "Run", "<", "?", ",", "?", ">", "run", ")", "{", "if", "(", "proxySettings", "!=", "null", "&&", "proxySettings", ".", "getFsProxyCredentialsId", "(", ")", "!=", "null", ")", "{", "UsernamePasswordCredentials", ...
Get credentials by the credentials id. Then set the user name and password into the SsePoxySetting.
[ "Get", "credentials", "by", "the", "credentials", "id", ".", "Then", "set", "the", "user", "name", "and", "password", "into", "the", "SsePoxySetting", "." ]
987536f5551bc76fd028d746a951d1fd72c7567a
https://github.com/hpsa/hpe-application-automation-tools-plugin/blob/987536f5551bc76fd028d746a951d1fd72c7567a/src/main/java/com/hp/application/automation/tools/run/SseBuilder.java#L177-L190
36,999
hpsa/hpe-application-automation-tools-plugin
src/main/java/com/hp/application/automation/tools/run/SseBuilder.java
SseBuilder.getCredentialsById
private UsernamePasswordCredentials getCredentialsById(String credentialsId, Run<?, ?> run, PrintStream logger) { if (StringUtils.isBlank(credentialsId)) { throw new NullPointerException("credentials is not configured."); } UsernamePasswordCredentials credentials = CredentialsProvider.findCredentialById(credentialsId, StandardUsernamePasswordCredentials.class, run, URIRequirementBuilder.create().build()); if (credentials == null) { logger.println("Can not find credentials with the credentialsId:" + credentialsId); } return credentials; }
java
private UsernamePasswordCredentials getCredentialsById(String credentialsId, Run<?, ?> run, PrintStream logger) { if (StringUtils.isBlank(credentialsId)) { throw new NullPointerException("credentials is not configured."); } UsernamePasswordCredentials credentials = CredentialsProvider.findCredentialById(credentialsId, StandardUsernamePasswordCredentials.class, run, URIRequirementBuilder.create().build()); if (credentials == null) { logger.println("Can not find credentials with the credentialsId:" + credentialsId); } return credentials; }
[ "private", "UsernamePasswordCredentials", "getCredentialsById", "(", "String", "credentialsId", ",", "Run", "<", "?", ",", "?", ">", "run", ",", "PrintStream", "logger", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "credentialsId", ")", ")", "{", ...
Get user name password credentials by id.
[ "Get", "user", "name", "password", "credentials", "by", "id", "." ]
987536f5551bc76fd028d746a951d1fd72c7567a
https://github.com/hpsa/hpe-application-automation-tools-plugin/blob/987536f5551bc76fd028d746a951d1fd72c7567a/src/main/java/com/hp/application/automation/tools/run/SseBuilder.java#L195-L209