code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private void executeInParallel(Collection<Object> objList, String description, final Callback callback) {
SimultaneousExecutor executor = new SimultaneousExecutor(threadsPerCpu, getClass(), description);
for(final Object obj : objList) {
executor.execute(() -> callback.call(obj));
}
try {
executor.awaitSuccessfulCompletion();
} catch(Exception e) {
throw new RuntimeException(e);
}
} } | public class class_name {
private void executeInParallel(Collection<Object> objList, String description, final Callback callback) {
SimultaneousExecutor executor = new SimultaneousExecutor(threadsPerCpu, getClass(), description);
for(final Object obj : objList) {
executor.execute(() -> callback.call(obj)); // depends on control dependency: [for], data = [obj]
}
try {
executor.awaitSuccessfulCompletion(); // depends on control dependency: [try], data = [none]
} catch(Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public EClass getIfcObjective() {
if (ifcObjectiveEClass == null) {
ifcObjectiveEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(392);
}
return ifcObjectiveEClass;
} } | public class class_name {
@Override
public EClass getIfcObjective() {
if (ifcObjectiveEClass == null) {
ifcObjectiveEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(392);
// depends on control dependency: [if], data = [none]
}
return ifcObjectiveEClass;
} } |
public class class_name {
public final void mLONG() throws RecognitionException {
try {
int _type = LONG;
int _channel = DEFAULT_TOKEN_CHANNEL;
// druidG.g:727:6: ( ( NUM )+ )
// druidG.g:727:8: ( NUM )+
{
// druidG.g:727:8: ( NUM )+
int cnt42=0;
loop42:
while (true) {
int alt42=2;
int LA42_0 = input.LA(1);
if ( ((LA42_0 >= '0' && LA42_0 <= '9')) ) {
alt42=1;
}
switch (alt42) {
case 1 :
// druidG.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt42 >= 1 ) break loop42;
EarlyExitException eee = new EarlyExitException(42, input);
throw eee;
}
cnt42++;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } | public class class_name {
public final void mLONG() throws RecognitionException {
try {
int _type = LONG;
int _channel = DEFAULT_TOKEN_CHANNEL;
// druidG.g:727:6: ( ( NUM )+ )
// druidG.g:727:8: ( NUM )+
{
// druidG.g:727:8: ( NUM )+
int cnt42=0;
loop42:
while (true) {
int alt42=2;
int LA42_0 = input.LA(1);
if ( ((LA42_0 >= '0' && LA42_0 <= '9')) ) {
alt42=1; // depends on control dependency: [if], data = [none]
}
switch (alt42) {
case 1 :
// druidG.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume(); // depends on control dependency: [if], data = [none]
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse); // depends on control dependency: [if], data = [none]
throw mse;
}
}
break;
default :
if ( cnt42 >= 1 ) break loop42;
EarlyExitException eee = new EarlyExitException(42, input);
throw eee;
}
cnt42++; // depends on control dependency: [while], data = [none]
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } |
public class class_name {
private ReadResultEntry collectCachedEntries(long initialOffset, ReadResult readResult,
ArrayList<ReadResultEntryContents> cachedEntries) {
long expectedOffset = initialOffset;
while (readResult.hasNext()) {
ReadResultEntry entry = readResult.next();
if (entry.getType() == Cache) {
Preconditions.checkState(entry.getStreamSegmentOffset() == expectedOffset,
"Data returned from read was not contiguous.");
ReadResultEntryContents content = entry.getContent().getNow(null);
expectedOffset += content.getLength();
cachedEntries.add(content);
} else {
return entry;
}
}
return null;
} } | public class class_name {
private ReadResultEntry collectCachedEntries(long initialOffset, ReadResult readResult,
ArrayList<ReadResultEntryContents> cachedEntries) {
long expectedOffset = initialOffset;
while (readResult.hasNext()) {
ReadResultEntry entry = readResult.next();
if (entry.getType() == Cache) {
Preconditions.checkState(entry.getStreamSegmentOffset() == expectedOffset,
"Data returned from read was not contiguous."); // depends on control dependency: [if], data = [none]
ReadResultEntryContents content = entry.getContent().getNow(null);
expectedOffset += content.getLength(); // depends on control dependency: [if], data = [none]
cachedEntries.add(content); // depends on control dependency: [if], data = [none]
} else {
return entry; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
private String getChunk(final String string, final int slength,
final int marker) {
if (isDigit(string.charAt(marker))) {
return getNumericChunk(string, slength, marker);
} else {
return getTextChunk(string, slength, marker);
}
} } | public class class_name {
private String getChunk(final String string, final int slength,
final int marker) {
if (isDigit(string.charAt(marker))) {
return getNumericChunk(string, slength, marker); // depends on control dependency: [if], data = [none]
} else {
return getTextChunk(string, slength, marker); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void load(final String key, final String value, final String location) {
// Recursive bit
if (INCLUDE.equals(key)) {
load(parseStringArray(value));
} else {
backing.put(key, value);
if ("yes".equals(value) || "true".equals(value)) {
booleanBacking.add(key);
} else {
booleanBacking.remove(key);
}
String history = locations.get(key);
if (history == null) {
history = location;
} else {
history = location + "; " + history;
}
locations.put(key, history);
}
} } | public class class_name {
private void load(final String key, final String value, final String location) {
// Recursive bit
if (INCLUDE.equals(key)) {
load(parseStringArray(value)); // depends on control dependency: [if], data = [none]
} else {
backing.put(key, value); // depends on control dependency: [if], data = [none]
if ("yes".equals(value) || "true".equals(value)) {
booleanBacking.add(key); // depends on control dependency: [if], data = [none]
} else {
booleanBacking.remove(key); // depends on control dependency: [if], data = [none]
}
String history = locations.get(key);
if (history == null) {
history = location; // depends on control dependency: [if], data = [none]
} else {
history = location + "; " + history; // depends on control dependency: [if], data = [none]
}
locations.put(key, history); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void printDAS(PrintWriter pw)
{
DAS myDAS = null;
try {
myDAS = this.getDAS();
myDAS.print(pw);
} catch (DASException dasE) {
pw.println("\n\nCould not get a DAS object to print!\n" +
"DDS.getDAS() threw an Exception. Message: \n" +
dasE.getMessage());
}
} } | public class class_name {
public void printDAS(PrintWriter pw)
{
DAS myDAS = null;
try {
myDAS = this.getDAS(); // depends on control dependency: [try], data = [none]
myDAS.print(pw); // depends on control dependency: [try], data = [none]
} catch (DASException dasE) {
pw.println("\n\nCould not get a DAS object to print!\n" +
"DDS.getDAS() threw an Exception. Message: \n" +
dasE.getMessage());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setSubTitleColor(final Color COLOR) {
if (null == subTitleColor) {
_subTitleColor = COLOR;
fireUpdateEvent(REDRAW_EVENT);
} else {
subTitleColor.set(COLOR);
}
} } | public class class_name {
public void setSubTitleColor(final Color COLOR) {
if (null == subTitleColor) {
_subTitleColor = COLOR; // depends on control dependency: [if], data = [none]
fireUpdateEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none]
} else {
subTitleColor.set(COLOR); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void execute( Sftp sftp ) throws JSchException, IOException {
logger.debug( "executing sftp command on {}", sessionManager );
ChannelSftp channelSftp = null;
try {
channelSftp = (ChannelSftp) sessionManager.getSession()
.openChannel( CHANNEL_SFTP );
channelSftp.connect();
sftp.run( channelSftp );
}
finally {
if ( channelSftp != null ) {
channelSftp.disconnect();
}
}
} } | public class class_name {
public void execute( Sftp sftp ) throws JSchException, IOException {
logger.debug( "executing sftp command on {}", sessionManager );
ChannelSftp channelSftp = null;
try {
channelSftp = (ChannelSftp) sessionManager.getSession()
.openChannel( CHANNEL_SFTP );
channelSftp.connect();
sftp.run( channelSftp );
}
finally {
if ( channelSftp != null ) {
channelSftp.disconnect(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public void init() {
if (CmsImageLoader.isEnabled()) {
try {
//reads the optional parameters for the gallery from the XML configuration
I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(GALLERYTYPE_NAME);
if (type instanceof CmsResourceTypeFolderExtended) {
m_galleryTypeParams = ((CmsResourceTypeFolderExtended)type).getFolderClassParams();
} else {
m_galleryTypeParams = null;
}
} catch (CmsLoaderException e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e);
}
}
m_defaultScaleParams = new CmsImageScaler(m_galleryTypeParams);
if (!m_defaultScaleParams.isValid()) {
// no valid parameters have been provided, use defaults
m_defaultScaleParams.setType(0);
m_defaultScaleParams.setPosition(0);
m_defaultScaleParams.setWidth(120);
m_defaultScaleParams.setHeight(90);
m_defaultScaleParams.setColor(new Color(221, 221, 221));
}
} else {
m_defaultScaleParams = null;
}
} } | public class class_name {
@Override
public void init() {
if (CmsImageLoader.isEnabled()) {
try {
//reads the optional parameters for the gallery from the XML configuration
I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(GALLERYTYPE_NAME);
if (type instanceof CmsResourceTypeFolderExtended) {
m_galleryTypeParams = ((CmsResourceTypeFolderExtended)type).getFolderClassParams(); // depends on control dependency: [if], data = [none]
} else {
m_galleryTypeParams = null; // depends on control dependency: [if], data = [none]
}
} catch (CmsLoaderException e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
m_defaultScaleParams = new CmsImageScaler(m_galleryTypeParams); // depends on control dependency: [if], data = [none]
if (!m_defaultScaleParams.isValid()) {
// no valid parameters have been provided, use defaults
m_defaultScaleParams.setType(0); // depends on control dependency: [if], data = [none]
m_defaultScaleParams.setPosition(0); // depends on control dependency: [if], data = [none]
m_defaultScaleParams.setWidth(120); // depends on control dependency: [if], data = [none]
m_defaultScaleParams.setHeight(90); // depends on control dependency: [if], data = [none]
m_defaultScaleParams.setColor(new Color(221, 221, 221)); // depends on control dependency: [if], data = [none]
}
} else {
m_defaultScaleParams = null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static public ArrayDouble.D2 makeXEdgesRotated(ArrayDouble.D2 midx) {
int[] shape = midx.getShape();
int ny = shape[0];
int nx = shape[1];
ArrayDouble.D2 edgex = new ArrayDouble.D2(ny + 2, nx + 1);
// compute the interior rows
for (int y = 0; y < ny; y++) {
for (int x = 1; x < nx; x++) {
double xval = (midx.get(y, x - 1) + midx.get(y, x)) / 2;
edgex.set(y + 1, x, xval);
}
edgex.set(y + 1, 0, midx.get(y, 0) - (edgex.get(y + 1, 1) - midx.get(y, 0)));
edgex.set(y + 1, nx, midx.get(y, nx - 1) - (edgex.get(y + 1, nx - 1) - midx.get(y, nx - 1)));
}
// compute the first row
for (int x = 0; x < nx; x++) {
edgex.set(0, x, midx.get(0, x));
}
// compute the last row
for (int x = 0; x < nx - 1; x++) {
edgex.set(ny + 1, x, midx.get(ny - 1, x));
}
return edgex;
} } | public class class_name {
static public ArrayDouble.D2 makeXEdgesRotated(ArrayDouble.D2 midx) {
int[] shape = midx.getShape();
int ny = shape[0];
int nx = shape[1];
ArrayDouble.D2 edgex = new ArrayDouble.D2(ny + 2, nx + 1);
// compute the interior rows
for (int y = 0; y < ny; y++) {
for (int x = 1; x < nx; x++) {
double xval = (midx.get(y, x - 1) + midx.get(y, x)) / 2;
edgex.set(y + 1, x, xval);
// depends on control dependency: [for], data = [x]
}
edgex.set(y + 1, 0, midx.get(y, 0) - (edgex.get(y + 1, 1) - midx.get(y, 0)));
// depends on control dependency: [for], data = [y]
edgex.set(y + 1, nx, midx.get(y, nx - 1) - (edgex.get(y + 1, nx - 1) - midx.get(y, nx - 1)));
// depends on control dependency: [for], data = [y]
}
// compute the first row
for (int x = 0; x < nx; x++) {
edgex.set(0, x, midx.get(0, x));
// depends on control dependency: [for], data = [x]
}
// compute the last row
for (int x = 0; x < nx - 1; x++) {
edgex.set(ny + 1, x, midx.get(ny - 1, x));
// depends on control dependency: [for], data = [x]
}
return edgex;
} } |
public class class_name {
public ResourceType getResourceType(final HttpServletRequest request) {
Validate.notNull(request);
final String uri = request.getRequestURI();
Validate.notNull(uri);
ResourceType type = null;
try {
type = ResourceType.get(FilenameUtils.getExtension(stripSessionID(uri)));
} catch (final IllegalArgumentException e) {
LOG.debug("[FAIL] Cannot identify resourceType for uri: {}", uri);
}
return type;
} } | public class class_name {
public ResourceType getResourceType(final HttpServletRequest request) {
Validate.notNull(request);
final String uri = request.getRequestURI();
Validate.notNull(uri);
ResourceType type = null;
try {
type = ResourceType.get(FilenameUtils.getExtension(stripSessionID(uri))); // depends on control dependency: [try], data = [none]
} catch (final IllegalArgumentException e) {
LOG.debug("[FAIL] Cannot identify resourceType for uri: {}", uri);
} // depends on control dependency: [catch], data = [none]
return type;
} } |
public class class_name {
public void marshall(DashConfiguration dashConfiguration, ProtocolMarshaller protocolMarshaller) {
if (dashConfiguration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(dashConfiguration.getManifestEndpointPrefix(), MANIFESTENDPOINTPREFIX_BINDING);
protocolMarshaller.marshall(dashConfiguration.getMpdLocation(), MPDLOCATION_BINDING);
protocolMarshaller.marshall(dashConfiguration.getOriginManifestType(), ORIGINMANIFESTTYPE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DashConfiguration dashConfiguration, ProtocolMarshaller protocolMarshaller) {
if (dashConfiguration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(dashConfiguration.getManifestEndpointPrefix(), MANIFESTENDPOINTPREFIX_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(dashConfiguration.getMpdLocation(), MPDLOCATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(dashConfiguration.getOriginManifestType(), ORIGINMANIFESTTYPE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(NonCompliantSummary nonCompliantSummary, ProtocolMarshaller protocolMarshaller) {
if (nonCompliantSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(nonCompliantSummary.getNonCompliantCount(), NONCOMPLIANTCOUNT_BINDING);
protocolMarshaller.marshall(nonCompliantSummary.getSeveritySummary(), SEVERITYSUMMARY_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(NonCompliantSummary nonCompliantSummary, ProtocolMarshaller protocolMarshaller) {
if (nonCompliantSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(nonCompliantSummary.getNonCompliantCount(), NONCOMPLIANTCOUNT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(nonCompliantSummary.getSeveritySummary(), SEVERITYSUMMARY_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public boolean isBinary() throws IOException {
InputStream is = getInputStream();
try {
byte[] bytes = new byte[3];
int count = is.read(bytes);
ByteOrderMask bom = ByteOrderMask.valueOf(bytes, 0, count);
if(bom != null){
return false;
}
while(true){
int i = is.read();
switch(i){
case -1:
return false;
case 0:
return true;
default:
break;
}
}
} finally {
is.close();
}
} } | public class class_name {
public boolean isBinary() throws IOException {
InputStream is = getInputStream();
try {
byte[] bytes = new byte[3];
int count = is.read(bytes);
ByteOrderMask bom = ByteOrderMask.valueOf(bytes, 0, count);
if(bom != null){
return false; // depends on control dependency: [if], data = [none]
}
while(true){
int i = is.read();
switch(i){
case -1:
return false;
case 0:
return true;
default:
break;
}
}
} finally {
is.close();
}
} } |
public class class_name {
private final void parseTargetSpecificSettings (final Element root) {
final NodeList targets = root.getElementsByTagName(ELEMENT_TARGET);
Node target;
Node parameter;
NodeList parameters;
try {
for (int i = 0; i < targets.getLength(); i++) {
target = targets.item(i);
parameters = target.getChildNodes();
// extract target address and the port (if specified)
SessionConfiguration sc = new SessionConfiguration();
sc.setAddress(target.getAttributes().getNamedItem(ATTRIBUTE_ADDRESS).getNodeValue(), Integer.parseInt(target.getAttributes().getNamedItem(ATTRIBUTE_PORT).getNodeValue()));
// extract the parameters for this target
for (int j = 0; j < parameters.getLength(); j++) {
parameter = parameters.item(j);
if (parameter.getNodeType() == Node.ELEMENT_NODE) {
sc.addSessionSetting(OperationalTextKey.valueOfEx(parameter.getNodeName()), parameter.getTextContent());
}
}
synchronized (sessionConfigs) {
sessionConfigs.put(target.getAttributes().getNamedItem(ATTRIBUTE_ID).getNodeValue(), sc);
}
}
} catch (UnknownHostException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("The given host is not reachable: " + e.getLocalizedMessage());
}
}
} } | public class class_name {
private final void parseTargetSpecificSettings (final Element root) {
final NodeList targets = root.getElementsByTagName(ELEMENT_TARGET);
Node target;
Node parameter;
NodeList parameters;
try {
for (int i = 0; i < targets.getLength(); i++) {
target = targets.item(i); // depends on control dependency: [for], data = [i]
parameters = target.getChildNodes(); // depends on control dependency: [for], data = [none]
// extract target address and the port (if specified)
SessionConfiguration sc = new SessionConfiguration();
sc.setAddress(target.getAttributes().getNamedItem(ATTRIBUTE_ADDRESS).getNodeValue(), Integer.parseInt(target.getAttributes().getNamedItem(ATTRIBUTE_PORT).getNodeValue())); // depends on control dependency: [for], data = [none]
// extract the parameters for this target
for (int j = 0; j < parameters.getLength(); j++) {
parameter = parameters.item(j); // depends on control dependency: [for], data = [j]
if (parameter.getNodeType() == Node.ELEMENT_NODE) {
sc.addSessionSetting(OperationalTextKey.valueOfEx(parameter.getNodeName()), parameter.getTextContent()); // depends on control dependency: [if], data = [none]
}
}
synchronized (sessionConfigs) { // depends on control dependency: [for], data = [none]
sessionConfigs.put(target.getAttributes().getNamedItem(ATTRIBUTE_ID).getNodeValue(), sc);
}
}
} catch (UnknownHostException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("The given host is not reachable: " + e.getLocalizedMessage()); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String journalIdBytesToString(byte[] jid) {
char[] charArray = new char[jid.length];
for (int i = 0; i < jid.length; i++) {
charArray[i] = (char) jid[i];
}
return new String(charArray, 0, charArray.length);
} } | public class class_name {
public static String journalIdBytesToString(byte[] jid) {
char[] charArray = new char[jid.length];
for (int i = 0; i < jid.length; i++) {
charArray[i] = (char) jid[i]; // depends on control dependency: [for], data = [i]
}
return new String(charArray, 0, charArray.length);
} } |
public class class_name {
public void initializeOfferings() {
FindIterable<Document> offerings = this.offeringsCollection.find();
for (Document d : offerings) {
offeringNames.add((String) d.get("offering_name"));
}
} } | public class class_name {
public void initializeOfferings() {
FindIterable<Document> offerings = this.offeringsCollection.find();
for (Document d : offerings) {
offeringNames.add((String) d.get("offering_name")); // depends on control dependency: [for], data = [d]
}
} } |
public class class_name {
@Override
public void shutdown() {
final WireMockServer server = this;
Thread shutdownThread = new Thread(new Runnable() {
@Override
public void run() {
try {
// We have to sleep briefly to finish serving the shutdown request before stopping the server, as
// there's no support in Jetty for shutting down after the current request.
// See http://stackoverflow.com/questions/4650713
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
server.stop();
}
});
shutdownThread.start();
} } | public class class_name {
@Override
public void shutdown() {
final WireMockServer server = this;
Thread shutdownThread = new Thread(new Runnable() {
@Override
public void run() {
try {
// We have to sleep briefly to finish serving the shutdown request before stopping the server, as
// there's no support in Jetty for shutting down after the current request.
// See http://stackoverflow.com/questions/4650713
Thread.sleep(100); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
server.stop();
}
});
shutdownThread.start();
} } |
public class class_name {
private long parseLastModified(HttpResponse response) {
Header header = response.getLastHeader("Last-Modified");
if (header == null) {
return 0;
}
String value = header.getValue();
if (value == null || value.isEmpty()) {
return 0;
}
Date date = DateUtils.parseDate(value);
if (date == null) {
return 0;
}
return date.getTime();
} } | public class class_name {
private long parseLastModified(HttpResponse response) {
Header header = response.getLastHeader("Last-Modified");
if (header == null) {
return 0; // depends on control dependency: [if], data = [none]
}
String value = header.getValue();
if (value == null || value.isEmpty()) {
return 0; // depends on control dependency: [if], data = [none]
}
Date date = DateUtils.parseDate(value);
if (date == null) {
return 0; // depends on control dependency: [if], data = [none]
}
return date.getTime();
} } |
public class class_name {
private String buildSelectClause() {
StringBuilder sqlBuf = new StringBuilder();
sqlBuf.append("SELECT ");
String column = null;
for (Enumeration select = mColumns.elements(); select.hasMoreElements();) {
column = (String) select.nextElement();
/*
String subColumn = column.substring(column.indexOf(".") + 1);
// System.err.println("DEBUG: col=" + subColumn);
String mapType = (String) mMapTypes.get(mColumnMap.get(subColumn));
*/
String mapType = (String) mMapTypes.get(getProperty(column));
if (mapType == null || mapType.equals(DIRECTMAP)) {
sqlBuf.append(column);
sqlBuf.append(select.hasMoreElements() ? ", " : " ");
}
}
return sqlBuf.toString();
} } | public class class_name {
private String buildSelectClause() {
StringBuilder sqlBuf = new StringBuilder();
sqlBuf.append("SELECT ");
String column = null;
for (Enumeration select = mColumns.elements(); select.hasMoreElements();) {
column = (String) select.nextElement();
// depends on control dependency: [for], data = [select]
/*
String subColumn = column.substring(column.indexOf(".") + 1);
// System.err.println("DEBUG: col=" + subColumn);
String mapType = (String) mMapTypes.get(mColumnMap.get(subColumn));
*/
String mapType = (String) mMapTypes.get(getProperty(column));
if (mapType == null || mapType.equals(DIRECTMAP)) {
sqlBuf.append(column);
// depends on control dependency: [if], data = [none]
sqlBuf.append(select.hasMoreElements() ? ", " : " ");
// depends on control dependency: [if], data = [none]
}
}
return sqlBuf.toString();
} } |
public class class_name {
protected List<List<GroovyRowResult>> callWithRows(String sql, List<Object> params, int processResultsSets, Closure closure) throws SQLException {
Connection connection = createConnection();
CallableStatement statement = null;
List<GroovyResultSet> resultSetResources = new ArrayList<GroovyResultSet>();
try {
statement = connection.prepareCall(sql);
LOG.fine(sql + " | " + params);
setParameters(params, statement);
boolean hasResultSet = statement.execute();
List<Object> results = new ArrayList<Object>();
int indx = 0;
int inouts = 0;
for (Object value : params) {
if (value instanceof OutParameter) {
if (value instanceof ResultSetOutParameter) {
GroovyResultSet resultSet = CallResultSet.getImpl(statement, indx);
resultSetResources.add(resultSet);
results.add(resultSet);
} else {
Object o = statement.getObject(indx + 1);
if (o instanceof ResultSet) {
GroovyResultSet resultSet = new GroovyResultSetProxy((ResultSet) o).getImpl();
results.add(resultSet);
resultSetResources.add(resultSet);
} else {
results.add(o);
}
}
inouts++;
}
indx++;
}
closure.call(results.toArray(new Object[inouts]));
List<List<GroovyRowResult>> resultSets = new ArrayList<List<GroovyRowResult>>();
if (processResultsSets == NO_RESULT_SETS) {
resultSets.add(new ArrayList<GroovyRowResult>());
return resultSets;
}
//Check both hasResultSet and getMoreResults() because of differences in vendor behavior
if (!hasResultSet) {
hasResultSet = statement.getMoreResults();
}
while (hasResultSet && (processResultsSets != NO_RESULT_SETS)) {
resultSets.add(asList(sql, statement.getResultSet()));
if (processResultsSets == FIRST_RESULT_SET) {
break;
} else {
hasResultSet = statement.getMoreResults();
}
}
return resultSets;
} catch (SQLException e) {
LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
throw e;
} finally {
for (GroovyResultSet rs : resultSetResources) {
closeResources(null, null, rs);
}
closeResources(connection, statement);
}
} } | public class class_name {
protected List<List<GroovyRowResult>> callWithRows(String sql, List<Object> params, int processResultsSets, Closure closure) throws SQLException {
Connection connection = createConnection();
CallableStatement statement = null;
List<GroovyResultSet> resultSetResources = new ArrayList<GroovyResultSet>();
try {
statement = connection.prepareCall(sql);
LOG.fine(sql + " | " + params);
setParameters(params, statement);
boolean hasResultSet = statement.execute();
List<Object> results = new ArrayList<Object>();
int indx = 0;
int inouts = 0;
for (Object value : params) {
if (value instanceof OutParameter) {
if (value instanceof ResultSetOutParameter) {
GroovyResultSet resultSet = CallResultSet.getImpl(statement, indx);
resultSetResources.add(resultSet); // depends on control dependency: [if], data = [none]
results.add(resultSet); // depends on control dependency: [if], data = [none]
} else {
Object o = statement.getObject(indx + 1);
if (o instanceof ResultSet) {
GroovyResultSet resultSet = new GroovyResultSetProxy((ResultSet) o).getImpl();
results.add(resultSet); // depends on control dependency: [if], data = [none]
resultSetResources.add(resultSet); // depends on control dependency: [if], data = [none]
} else {
results.add(o); // depends on control dependency: [if], data = [none]
}
}
inouts++; // depends on control dependency: [if], data = [none]
}
indx++; // depends on control dependency: [for], data = [none]
}
closure.call(results.toArray(new Object[inouts]));
List<List<GroovyRowResult>> resultSets = new ArrayList<List<GroovyRowResult>>();
if (processResultsSets == NO_RESULT_SETS) {
resultSets.add(new ArrayList<GroovyRowResult>()); // depends on control dependency: [if], data = [none]
return resultSets; // depends on control dependency: [if], data = [none]
}
//Check both hasResultSet and getMoreResults() because of differences in vendor behavior
if (!hasResultSet) {
hasResultSet = statement.getMoreResults(); // depends on control dependency: [if], data = [none]
}
while (hasResultSet && (processResultsSets != NO_RESULT_SETS)) {
resultSets.add(asList(sql, statement.getResultSet())); // depends on control dependency: [while], data = [none]
if (processResultsSets == FIRST_RESULT_SET) {
break;
} else {
hasResultSet = statement.getMoreResults(); // depends on control dependency: [if], data = [none]
}
}
return resultSets;
} catch (SQLException e) {
LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
throw e;
} finally {
for (GroovyResultSet rs : resultSetResources) {
closeResources(null, null, rs); // depends on control dependency: [for], data = [rs]
}
closeResources(connection, statement);
}
} } |
public class class_name {
private static boolean renameIndexFiles(
final FileSystem outputFS,
final Path indexZipFilePath,
final Path finalIndexZipFilePath
)
{
try {
return RetryUtils.retry(
() -> {
final boolean needRename;
if (outputFS.exists(finalIndexZipFilePath)) {
// NativeS3FileSystem.rename won't overwrite, so we might need to delete the old index first
final FileStatus zipFile = outputFS.getFileStatus(indexZipFilePath);
final FileStatus finalIndexZipFile = outputFS.getFileStatus(finalIndexZipFilePath);
if (zipFile.getModificationTime() >= finalIndexZipFile.getModificationTime()
|| zipFile.getLen() != finalIndexZipFile.getLen()) {
log.info(
"File[%s / %s / %sB] existed, but wasn't the same as [%s / %s / %sB]",
finalIndexZipFile.getPath(),
DateTimes.utc(finalIndexZipFile.getModificationTime()),
finalIndexZipFile.getLen(),
zipFile.getPath(),
DateTimes.utc(zipFile.getModificationTime()),
zipFile.getLen()
);
outputFS.delete(finalIndexZipFilePath, false);
needRename = true;
} else {
log.info(
"File[%s / %s / %sB] existed and will be kept",
finalIndexZipFile.getPath(),
DateTimes.utc(finalIndexZipFile.getModificationTime()),
finalIndexZipFile.getLen()
);
needRename = false;
}
} else {
needRename = true;
}
if (needRename) {
log.info("Attempting rename from [%s] to [%s]", indexZipFilePath, finalIndexZipFilePath);
return outputFS.rename(indexZipFilePath, finalIndexZipFilePath);
} else {
return true;
}
},
FileUtils.IS_EXCEPTION,
NUM_RETRIES
);
}
catch (Exception e) {
throw new RuntimeException(e);
}
} } | public class class_name {
private static boolean renameIndexFiles(
final FileSystem outputFS,
final Path indexZipFilePath,
final Path finalIndexZipFilePath
)
{
try {
return RetryUtils.retry(
() -> {
final boolean needRename;
if (outputFS.exists(finalIndexZipFilePath)) {
// NativeS3FileSystem.rename won't overwrite, so we might need to delete the old index first
final FileStatus zipFile = outputFS.getFileStatus(indexZipFilePath);
final FileStatus finalIndexZipFile = outputFS.getFileStatus(finalIndexZipFilePath);
if (zipFile.getModificationTime() >= finalIndexZipFile.getModificationTime()
|| zipFile.getLen() != finalIndexZipFile.getLen()) {
log.info(
"File[%s / %s / %sB] existed, but wasn't the same as [%s / %s / %sB]",
finalIndexZipFile.getPath(),
DateTimes.utc(finalIndexZipFile.getModificationTime()),
finalIndexZipFile.getLen(),
zipFile.getPath(),
DateTimes.utc(zipFile.getModificationTime()),
zipFile.getLen()
); // depends on control dependency: [if], data = [none]
outputFS.delete(finalIndexZipFilePath, false); // depends on control dependency: [if], data = [none]
needRename = true; // depends on control dependency: [if], data = [none]
} else {
log.info(
"File[%s / %s / %sB] existed and will be kept",
finalIndexZipFile.getPath(),
DateTimes.utc(finalIndexZipFile.getModificationTime()),
finalIndexZipFile.getLen()
); // depends on control dependency: [if], data = [none]
needRename = false; // depends on control dependency: [if], data = [none]
}
} else {
needRename = true; // depends on control dependency: [if], data = [none]
}
if (needRename) {
log.info("Attempting rename from [%s] to [%s]", indexZipFilePath, finalIndexZipFilePath); // depends on control dependency: [if], data = [none]
return outputFS.rename(indexZipFilePath, finalIndexZipFilePath); // depends on control dependency: [if], data = [none]
} else {
return true; // depends on control dependency: [if], data = [none]
}
},
FileUtils.IS_EXCEPTION,
NUM_RETRIES
);
}
catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private List<CLIQUESubspace> findDenseSubspaceCandidates(Relation<? extends NumberVector> database, List<CLIQUESubspace> denseSubspaces) {
// sort (k-1)-dimensional dense subspace according to their dimensions
List<CLIQUESubspace> denseSubspacesByDimensions = new ArrayList<>(denseSubspaces);
Collections.sort(denseSubspacesByDimensions, Subspace.DIMENSION_COMPARATOR);
// determine k-dimensional dense subspace candidates
double all = database.size();
List<CLIQUESubspace> denseSubspaceCandidates = new ArrayList<>();
while(!denseSubspacesByDimensions.isEmpty()) {
CLIQUESubspace s1 = denseSubspacesByDimensions.remove(0);
for(CLIQUESubspace s2 : denseSubspacesByDimensions) {
CLIQUESubspace s = s1.join(s2, all, tau);
if(s != null) {
denseSubspaceCandidates.add(s);
}
}
}
// sort reverse by coverage
Collections.sort(denseSubspaceCandidates, CLIQUESubspace.BY_COVERAGE);
return denseSubspaceCandidates;
} } | public class class_name {
private List<CLIQUESubspace> findDenseSubspaceCandidates(Relation<? extends NumberVector> database, List<CLIQUESubspace> denseSubspaces) {
// sort (k-1)-dimensional dense subspace according to their dimensions
List<CLIQUESubspace> denseSubspacesByDimensions = new ArrayList<>(denseSubspaces);
Collections.sort(denseSubspacesByDimensions, Subspace.DIMENSION_COMPARATOR);
// determine k-dimensional dense subspace candidates
double all = database.size();
List<CLIQUESubspace> denseSubspaceCandidates = new ArrayList<>();
while(!denseSubspacesByDimensions.isEmpty()) {
CLIQUESubspace s1 = denseSubspacesByDimensions.remove(0);
for(CLIQUESubspace s2 : denseSubspacesByDimensions) {
CLIQUESubspace s = s1.join(s2, all, tau);
if(s != null) {
denseSubspaceCandidates.add(s); // depends on control dependency: [if], data = [(s]
}
}
}
// sort reverse by coverage
Collections.sort(denseSubspaceCandidates, CLIQUESubspace.BY_COVERAGE);
return denseSubspaceCandidates;
} } |
public class class_name {
protected void repaint(int t)
{
if (container != null)
{
Rectangle bounds = owner.getAbsoluteBounds();
container.repaint(t, bounds.x, bounds.y, bounds.width, bounds.height);
}
} } | public class class_name {
protected void repaint(int t)
{
if (container != null)
{
Rectangle bounds = owner.getAbsoluteBounds();
container.repaint(t, bounds.x, bounds.y, bounds.width, bounds.height); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void onUpdate(EventLog log)
{
if (updateEvents == null)
{
updateEvents = new ConcurrentHashMap<Object, EventLog>();
}
updateEvents.put(log.getEntityId(), log);
} } | public class class_name {
private void onUpdate(EventLog log)
{
if (updateEvents == null)
{
updateEvents = new ConcurrentHashMap<Object, EventLog>(); // depends on control dependency: [if], data = [none]
}
updateEvents.put(log.getEntityId(), log);
} } |
public class class_name {
int subSimplify(PointList points, int fromIndex, int lastIndex) {
if (lastIndex - fromIndex < 2) {
return 0;
}
int indexWithMaxDist = -1;
double maxDist = -1;
double firstLat = points.getLatitude(fromIndex);
double firstLon = points.getLongitude(fromIndex);
double lastLat = points.getLatitude(lastIndex);
double lastLon = points.getLongitude(lastIndex);
for (int i = fromIndex + 1; i < lastIndex; i++) {
double lat = points.getLatitude(i);
if (Double.isNaN(lat)) {
continue;
}
double lon = points.getLongitude(i);
double dist = calc.calcNormalizedEdgeDistance(lat, lon, firstLat, firstLon, lastLat, lastLon);
if (maxDist < dist) {
indexWithMaxDist = i;
maxDist = dist;
}
}
if (indexWithMaxDist < 0) {
throw new IllegalStateException("maximum not found in [" + fromIndex + "," + lastIndex + "]");
}
int counter = 0;
if (maxDist < normedMaxDist) {
for (int i = fromIndex + 1; i < lastIndex; i++) {
points.set(i, Double.NaN, Double.NaN, Double.NaN);
counter++;
}
} else {
counter = subSimplify(points, fromIndex, indexWithMaxDist);
counter += subSimplify(points, indexWithMaxDist, lastIndex);
}
return counter;
} } | public class class_name {
int subSimplify(PointList points, int fromIndex, int lastIndex) {
if (lastIndex - fromIndex < 2) {
return 0; // depends on control dependency: [if], data = [none]
}
int indexWithMaxDist = -1;
double maxDist = -1;
double firstLat = points.getLatitude(fromIndex);
double firstLon = points.getLongitude(fromIndex);
double lastLat = points.getLatitude(lastIndex);
double lastLon = points.getLongitude(lastIndex);
for (int i = fromIndex + 1; i < lastIndex; i++) {
double lat = points.getLatitude(i);
if (Double.isNaN(lat)) {
continue;
}
double lon = points.getLongitude(i);
double dist = calc.calcNormalizedEdgeDistance(lat, lon, firstLat, firstLon, lastLat, lastLon);
if (maxDist < dist) {
indexWithMaxDist = i; // depends on control dependency: [if], data = [none]
maxDist = dist; // depends on control dependency: [if], data = [none]
}
}
if (indexWithMaxDist < 0) {
throw new IllegalStateException("maximum not found in [" + fromIndex + "," + lastIndex + "]");
}
int counter = 0;
if (maxDist < normedMaxDist) {
for (int i = fromIndex + 1; i < lastIndex; i++) {
points.set(i, Double.NaN, Double.NaN, Double.NaN); // depends on control dependency: [for], data = [i]
counter++; // depends on control dependency: [for], data = [none]
}
} else {
counter = subSimplify(points, fromIndex, indexWithMaxDist); // depends on control dependency: [if], data = [none]
counter += subSimplify(points, indexWithMaxDist, lastIndex); // depends on control dependency: [if], data = [none]
}
return counter;
} } |
public class class_name {
@Nullable
public static Drawable tint(Context context, @DrawableRes int drawableId, @AttrRes int attrId) {
Drawable d = context.getDrawable(drawableId);
if (d != null) {
d.setTint(Themes.getColor(context, attrId));
}
return d;
} } | public class class_name {
@Nullable
public static Drawable tint(Context context, @DrawableRes int drawableId, @AttrRes int attrId) {
Drawable d = context.getDrawable(drawableId);
if (d != null) {
d.setTint(Themes.getColor(context, attrId)); // depends on control dependency: [if], data = [none]
}
return d;
} } |
public class class_name {
private static Method[] getAllPublicMethods(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("You must specify a class in order to get the methods.");
}
Set<Method> methods = new LinkedHashSet<Method>();
for (Method method : clazz.getMethods()) {
method.setAccessible(true);
methods.add(method);
}
return methods.toArray(new Method[0]);
} } | public class class_name {
private static Method[] getAllPublicMethods(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("You must specify a class in order to get the methods.");
}
Set<Method> methods = new LinkedHashSet<Method>();
for (Method method : clazz.getMethods()) {
method.setAccessible(true); // depends on control dependency: [for], data = [method]
methods.add(method); // depends on control dependency: [for], data = [method]
}
return methods.toArray(new Method[0]);
} } |
public class class_name {
public void recountRecords()
{
try {
Object bookmark = null;
if (m_bRestoreCurrentRecord)
if (m_recordSub.getEditMode() == DBConstants.EDIT_CURRENT)
bookmark = m_recordSub.getHandle(DBConstants.BOOKMARK_HANDLE);
m_recordSub.close();
while (m_recordSub.hasNext())
{ // Recount each sub-record
m_recordSub.next();
}
if (bookmark != null)
m_recordSub.setHandle(bookmark, DBConstants.BOOKMARK_HANDLE);
} catch (DBException ex) {
ex.printStackTrace();
}
} } | public class class_name {
public void recountRecords()
{
try {
Object bookmark = null;
if (m_bRestoreCurrentRecord)
if (m_recordSub.getEditMode() == DBConstants.EDIT_CURRENT)
bookmark = m_recordSub.getHandle(DBConstants.BOOKMARK_HANDLE);
m_recordSub.close(); // depends on control dependency: [try], data = [none]
while (m_recordSub.hasNext())
{ // Recount each sub-record
m_recordSub.next(); // depends on control dependency: [while], data = [none]
}
if (bookmark != null)
m_recordSub.setHandle(bookmark, DBConstants.BOOKMARK_HANDLE);
} catch (DBException ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@SuppressWarnings("unchecked")
private static Collection<LogEntryValue>[][] calculateRequiredLogEntryValues(final Collection<Writer>[][] writers) {
Collection<LogEntryValue>[][] logEntryValues = new Collection[writers.length][Level.values().length - 1];
for (int tagIndex = 0; tagIndex < writers.length; ++tagIndex) {
for (int levelIndex = 0; levelIndex < Level.OFF.ordinal(); ++levelIndex) {
Set<LogEntryValue> values = EnumSet.noneOf(LogEntryValue.class);
for (Writer writer : writers[tagIndex][levelIndex]) {
values.addAll(writer.getRequiredLogEntryValues());
}
logEntryValues[tagIndex][levelIndex] = values;
}
}
return logEntryValues;
} } | public class class_name {
@SuppressWarnings("unchecked")
private static Collection<LogEntryValue>[][] calculateRequiredLogEntryValues(final Collection<Writer>[][] writers) {
Collection<LogEntryValue>[][] logEntryValues = new Collection[writers.length][Level.values().length - 1];
for (int tagIndex = 0; tagIndex < writers.length; ++tagIndex) {
for (int levelIndex = 0; levelIndex < Level.OFF.ordinal(); ++levelIndex) {
Set<LogEntryValue> values = EnumSet.noneOf(LogEntryValue.class);
for (Writer writer : writers[tagIndex][levelIndex]) {
values.addAll(writer.getRequiredLogEntryValues()); // depends on control dependency: [for], data = [writer]
}
logEntryValues[tagIndex][levelIndex] = values; // depends on control dependency: [for], data = [levelIndex]
}
}
return logEntryValues;
} } |
public class class_name {
public SimpleFeature convertDwgArc( String typeName, String layerName, DwgArc arc, int id ) {
double[] c = arc.getCenter();
Point2D center = new Point2D.Double(c[0], c[1]);
double radius = (arc).getRadius();
double initAngle = Math.toDegrees((arc).getInitAngle());
double endAngle = Math.toDegrees((arc).getEndAngle());
Point2D[] ptos = GisModelCurveCalculator.calculateGisModelArc(center, radius, initAngle,
endAngle);
CoordinateList coordList = new CoordinateList();
for( int j = 0; j < ptos.length; j++ ) {
Coordinate coord = new Coordinate(ptos[j].getX(), ptos[j].getY(), 0.0);
coordList.add(coord);
}
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.setName(typeName);
b.setCRS(crs);
b.add(THE_GEOM, LineString.class);
b.add(LAYER, String.class);
SimpleFeatureType type = b.buildFeatureType();
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
Geometry lineString = gF.createLineString(coordList.toCoordinateArray());
Object[] values = new Object[]{lineString, layerName};
builder.addAll(values);
return builder.buildFeature(typeName + "." + id);
} } | public class class_name {
public SimpleFeature convertDwgArc( String typeName, String layerName, DwgArc arc, int id ) {
double[] c = arc.getCenter();
Point2D center = new Point2D.Double(c[0], c[1]);
double radius = (arc).getRadius();
double initAngle = Math.toDegrees((arc).getInitAngle());
double endAngle = Math.toDegrees((arc).getEndAngle());
Point2D[] ptos = GisModelCurveCalculator.calculateGisModelArc(center, radius, initAngle,
endAngle);
CoordinateList coordList = new CoordinateList();
for( int j = 0; j < ptos.length; j++ ) {
Coordinate coord = new Coordinate(ptos[j].getX(), ptos[j].getY(), 0.0);
coordList.add(coord); // depends on control dependency: [for], data = [none]
}
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.setName(typeName);
b.setCRS(crs);
b.add(THE_GEOM, LineString.class);
b.add(LAYER, String.class);
SimpleFeatureType type = b.buildFeatureType();
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
Geometry lineString = gF.createLineString(coordList.toCoordinateArray());
Object[] values = new Object[]{lineString, layerName};
builder.addAll(values);
return builder.buildFeature(typeName + "." + id);
} } |
public class class_name {
@Override
public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver driver,
String editTable, SQLiteQuery query) {
// Create a standard cursor
Cursor cursor = new SQLiteCursor(driver, editTable, query);
// Check if there is an edit table
if (editTable != null) {
// Check if the table has a cursor wrapper
GeoPackageCursorWrapper cursorWrapper = tableCursors.get(editTable);
if (cursorWrapper != null) {
cursor = cursorWrapper.wrapCursor(cursor);
}
}
return cursor;
} } | public class class_name {
@Override
public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver driver,
String editTable, SQLiteQuery query) {
// Create a standard cursor
Cursor cursor = new SQLiteCursor(driver, editTable, query);
// Check if there is an edit table
if (editTable != null) {
// Check if the table has a cursor wrapper
GeoPackageCursorWrapper cursorWrapper = tableCursors.get(editTable);
if (cursorWrapper != null) {
cursor = cursorWrapper.wrapCursor(cursor); // depends on control dependency: [if], data = [none]
}
}
return cursor;
} } |
public class class_name {
private static Class<?> extractClass(Class<?> ownerClass, Type arg) {
if (arg instanceof ParameterizedType) {
return extractClass(ownerClass, ((ParameterizedType) arg).getRawType());
}
else if (arg instanceof GenericArrayType) {
GenericArrayType gat = (GenericArrayType) arg;
Type gt = gat.getGenericComponentType();
Class<?> componentClass = extractClass(ownerClass, gt);
return Array.newInstance(componentClass, 0).getClass();
}
else if (arg instanceof TypeVariable) {
TypeVariable tv = (TypeVariable) arg;
arg = getTypeVariableMap(ownerClass).get(tv);
if (arg == null) {
arg = extractBoundForTypeVariable(tv);
if (arg instanceof ParameterizedType) {
return extractClass(ownerClass, ((ParameterizedType) arg).getRawType());
}
}
else {
return extractClass(ownerClass, arg);
}
}
return (arg instanceof Class ? (Class) arg : Object.class);
} } | public class class_name {
private static Class<?> extractClass(Class<?> ownerClass, Type arg) {
if (arg instanceof ParameterizedType) {
return extractClass(ownerClass, ((ParameterizedType) arg).getRawType());
}
else if (arg instanceof GenericArrayType) {
GenericArrayType gat = (GenericArrayType) arg;
Type gt = gat.getGenericComponentType();
Class<?> componentClass = extractClass(ownerClass, gt);
return Array.newInstance(componentClass, 0).getClass();
}
else if (arg instanceof TypeVariable) {
TypeVariable tv = (TypeVariable) arg;
arg = getTypeVariableMap(ownerClass).get(tv);
if (arg == null) {
arg = extractBoundForTypeVariable(tv); // depends on control dependency: [if], data = [none]
if (arg instanceof ParameterizedType) {
return extractClass(ownerClass, ((ParameterizedType) arg).getRawType()); // depends on control dependency: [if], data = [none]
}
}
else {
return extractClass(ownerClass, arg); // depends on control dependency: [if], data = [none]
}
}
return (arg instanceof Class ? (Class) arg : Object.class);
} } |
public class class_name {
public static double logpdf(double x, double k, double theta, double shift) {
x = (x - shift);
if(x <= 0.) {
return Double.NEGATIVE_INFINITY;
}
final double log1px = FastMath.log1p(x);
return k * FastMath.log(theta) - GammaDistribution.logGamma(k) - (theta + 1.) * log1px + (k - 1) * FastMath.log(log1px);
} } | public class class_name {
public static double logpdf(double x, double k, double theta, double shift) {
x = (x - shift);
if(x <= 0.) {
return Double.NEGATIVE_INFINITY; // depends on control dependency: [if], data = [none]
}
final double log1px = FastMath.log1p(x);
return k * FastMath.log(theta) - GammaDistribution.logGamma(k) - (theta + 1.) * log1px + (k - 1) * FastMath.log(log1px);
} } |
public class class_name {
@Override
public void sawOpcode(int seen) {
if (seen == Const.INVOKEINTERFACE) {
String clsName = getClassConstantOperand();
String methodName = getNameConstantOperand();
if (queryClasses.contains(clsName) && queryMethods.contains(methodName)) {
queryLocations.add(Integer.valueOf(getPC()));
}
} else if (OpcodeUtils.isBranch(seen)) {
int branchTarget = getBranchTarget();
int pc = getPC();
if (branchTarget < pc) {
loops.add(new LoopLocation(branchTarget, pc));
}
}
} } | public class class_name {
@Override
public void sawOpcode(int seen) {
if (seen == Const.INVOKEINTERFACE) {
String clsName = getClassConstantOperand();
String methodName = getNameConstantOperand();
if (queryClasses.contains(clsName) && queryMethods.contains(methodName)) {
queryLocations.add(Integer.valueOf(getPC())); // depends on control dependency: [if], data = [none]
}
} else if (OpcodeUtils.isBranch(seen)) {
int branchTarget = getBranchTarget();
int pc = getPC();
if (branchTarget < pc) {
loops.add(new LoopLocation(branchTarget, pc)); // depends on control dependency: [if], data = [(branchTarget]
}
}
} } |
public class class_name {
public void setMinorTickSpace(final double SPACE) {
if (null == minorTickSpace) {
_minorTickSpace = SPACE;
fireUpdateEvent(RECALC_EVENT);
} else {
minorTickSpace.set(SPACE);
}
} } | public class class_name {
public void setMinorTickSpace(final double SPACE) {
if (null == minorTickSpace) {
_minorTickSpace = SPACE; // depends on control dependency: [if], data = [none]
fireUpdateEvent(RECALC_EVENT); // depends on control dependency: [if], data = [none]
} else {
minorTickSpace.set(SPACE); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public DrawerView clearFixedItems() {
for (DrawerItem item : mAdapterFixed.getItems()) {
item.detach();
}
mAdapterFixed.clear();
updateFixedList();
return this;
} } | public class class_name {
public DrawerView clearFixedItems() {
for (DrawerItem item : mAdapterFixed.getItems()) {
item.detach(); // depends on control dependency: [for], data = [item]
}
mAdapterFixed.clear();
updateFixedList();
return this;
} } |
public class class_name {
public static void closeQuietly(@Nullable Socket socket, @Nullable Writer writer) {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
closeQuietly(socket);
} } | public class class_name {
public static void closeQuietly(@Nullable Socket socket, @Nullable Writer writer) {
if (writer != null) {
try {
writer.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
} // depends on control dependency: [catch], data = [none]
}
closeQuietly(socket);
} } |
public class class_name {
@Override
public void applyFiltering(PngFilterType filterType, List<byte[]> scanlines, int sampleBitCount) {
int scanlineLength = scanlines.get(0).length;
byte[] previousRow = new byte[scanlineLength];
for (byte[] scanline : scanlines) {
if (filterType != null) {
scanline[0] = filterType.getValue();
}
byte[] previous = scanline.clone();
try {
this.filter(scanline, previousRow, sampleBitCount);
} catch (PngException e) {
this.log.error("Error during filtering: %s", e.getMessage());
}
previousRow = previous;
}
} } | public class class_name {
@Override
public void applyFiltering(PngFilterType filterType, List<byte[]> scanlines, int sampleBitCount) {
int scanlineLength = scanlines.get(0).length;
byte[] previousRow = new byte[scanlineLength];
for (byte[] scanline : scanlines) {
if (filterType != null) {
scanline[0] = filterType.getValue(); // depends on control dependency: [if], data = [none]
}
byte[] previous = scanline.clone();
try {
this.filter(scanline, previousRow, sampleBitCount); // depends on control dependency: [try], data = [none]
} catch (PngException e) {
this.log.error("Error during filtering: %s", e.getMessage());
} // depends on control dependency: [catch], data = [none]
previousRow = previous; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
private void cancelIncompleteOperations(Iterable<CompletableOperation> operations, Throwable failException) {
assert failException != null : "no exception to set";
int cancelCount = 0;
for (CompletableOperation o : operations) {
if (!o.isDone()) {
this.state.failOperation(o, failException);
cancelCount++;
}
}
log.warn("{}: Cancelling {} operations with exception: {}.", this.traceObjectId, cancelCount, failException.toString());
} } | public class class_name {
private void cancelIncompleteOperations(Iterable<CompletableOperation> operations, Throwable failException) {
assert failException != null : "no exception to set";
int cancelCount = 0;
for (CompletableOperation o : operations) {
if (!o.isDone()) {
this.state.failOperation(o, failException); // depends on control dependency: [if], data = [none]
cancelCount++; // depends on control dependency: [if], data = [none]
}
}
log.warn("{}: Cancelling {} operations with exception: {}.", this.traceObjectId, cancelCount, failException.toString());
} } |
public class class_name {
public static EntityMapper getEntityMapper(Class<?> entityClass) {
synchronized (entityClass) {
// 先从map中获取实体映射信息
EntityMapper entityMapper = tableMapperCache.get(entityClass);
// 如果存在直接返回
if (entityMapper != null) {
return entityMapper;
}
TableMapper tableMapper = getTableMapper(entityClass);
//获取实体ID泛型
Class<?> idClass = getIdClass(entityClass);
// 获取实体字段列表
List<Field> fields = getAllField(entityClass);
// 全部列
Set<ColumnMapper> columnMapperSet = new HashSet<ColumnMapper>();
// 主键
ColumnMapper idColumn = null;
GenerationType idStrategy = null;
for (Field field : fields) {
// 排除字段
if (field.isAnnotationPresent(Transient.class)) {
continue;
}
ColumnMapper columnMapper = new ColumnMapper();
// 数据库字段名
String columnName = null;
if (field.isAnnotationPresent(Column.class)) {
Column column = field.getAnnotation(Column.class);
columnName = column.name();
columnMapper.setInsertable(column.insertable());
columnMapper.setUpdatable(column.updatable());
}
// 如果为空,使用属性名并替换为下划线风格
if (columnName == null || columnName.equals("")) {
columnName = camelhumpToUnderline(field.getName());
}
columnMapper.setProperty(field.getName());
columnMapper.setColumn(columnName);
columnMapper.setJavaType(field.getType());
// 是否主键
if(field.isAnnotationPresent(Id.class)){
columnMapper.setId(true);
if(field.isAnnotationPresent(GeneratedValue.class)){
idStrategy = field.getAnnotation(GeneratedValue.class).strategy();
}
idColumn = columnMapper;
}
// 添加到所有字段映射信息
columnMapperSet.add(columnMapper);
}
if (columnMapperSet.size() <= 0) {
throw new RuntimeException("实体" + entityClass.getName() + "不存在映射字段");
}
if (idColumn == null) {
throw new RuntimeException("实体" + entityClass.getName() + "不存在主键");
}
// 解析实体映射信息
entityMapper = new EntityMapper();
entityMapper.setTableMapper(tableMapper);
entityMapper.setColumnsMapper(columnMapperSet);
entityMapper.setIdClass(idClass);
entityMapper.setIdColumn(idColumn);
entityMapper.setIdStrategy(idStrategy);
tableMapperCache.put(entityClass, entityMapper);
return entityMapper;
}
} } | public class class_name {
public static EntityMapper getEntityMapper(Class<?> entityClass) {
synchronized (entityClass) {
// 先从map中获取实体映射信息
EntityMapper entityMapper = tableMapperCache.get(entityClass);
// 如果存在直接返回
if (entityMapper != null) {
return entityMapper;
// depends on control dependency: [if], data = [none]
}
TableMapper tableMapper = getTableMapper(entityClass);
//获取实体ID泛型
Class<?> idClass = getIdClass(entityClass);
// 获取实体字段列表
List<Field> fields = getAllField(entityClass);
// 全部列
Set<ColumnMapper> columnMapperSet = new HashSet<ColumnMapper>();
// 主键
ColumnMapper idColumn = null;
GenerationType idStrategy = null;
for (Field field : fields) {
// 排除字段
if (field.isAnnotationPresent(Transient.class)) {
continue;
}
ColumnMapper columnMapper = new ColumnMapper();
// 数据库字段名
String columnName = null;
if (field.isAnnotationPresent(Column.class)) {
Column column = field.getAnnotation(Column.class);
columnName = column.name();
// depends on control dependency: [if], data = [none]
columnMapper.setInsertable(column.insertable());
// depends on control dependency: [if], data = [none]
columnMapper.setUpdatable(column.updatable());
// depends on control dependency: [if], data = [none]
}
// 如果为空,使用属性名并替换为下划线风格
if (columnName == null || columnName.equals("")) {
columnName = camelhumpToUnderline(field.getName());
// depends on control dependency: [if], data = [none]
}
columnMapper.setProperty(field.getName());
// depends on control dependency: [for], data = [field]
columnMapper.setColumn(columnName);
// depends on control dependency: [for], data = [none]
columnMapper.setJavaType(field.getType());
// depends on control dependency: [for], data = [field]
// 是否主键
if(field.isAnnotationPresent(Id.class)){
columnMapper.setId(true);
// depends on control dependency: [if], data = [none]
if(field.isAnnotationPresent(GeneratedValue.class)){
idStrategy = field.getAnnotation(GeneratedValue.class).strategy();
// depends on control dependency: [if], data = [none]
}
idColumn = columnMapper;
// depends on control dependency: [if], data = [none]
}
// 添加到所有字段映射信息
columnMapperSet.add(columnMapper);
// depends on control dependency: [for], data = [none]
}
if (columnMapperSet.size() <= 0) {
throw new RuntimeException("实体" + entityClass.getName() + "不存在映射字段");
}
if (idColumn == null) {
throw new RuntimeException("实体" + entityClass.getName() + "不存在主键");
}
// 解析实体映射信息
entityMapper = new EntityMapper();
entityMapper.setTableMapper(tableMapper);
entityMapper.setColumnsMapper(columnMapperSet);
entityMapper.setIdClass(idClass);
entityMapper.setIdColumn(idColumn);
entityMapper.setIdStrategy(idStrategy);
tableMapperCache.put(entityClass, entityMapper);
return entityMapper;
}
} } |
public class class_name {
public void readSource(String input) throws GraphVizException
{
StringBuilder sb = new StringBuilder();
try
{
FileInputStream fis = new FileInputStream(input);
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null)
{
sb.append(line);
}
dis.close();
} catch (Exception e)
{
throw new GraphVizException("Error: " + e.getMessage());
}
this.graph = sb;
} } | public class class_name {
public void readSource(String input) throws GraphVizException
{
StringBuilder sb = new StringBuilder();
try
{
FileInputStream fis = new FileInputStream(input);
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null)
{
sb.append(line); // depends on control dependency: [while], data = [none]
}
dis.close();
} catch (Exception e)
{
throw new GraphVizException("Error: " + e.getMessage());
}
this.graph = sb;
} } |
public class class_name {
private static void emitSpans(PrintWriter out, Formatter formatter, Collection<SpanData> spans) {
out.write("<pre>\n");
formatter.format("%-23s %18s%n", "When", "Elapsed(s)");
out.write("-------------------------------------------\n");
for (SpanData span : spans) {
tracer
.getCurrentSpan()
.addAnnotation(
"Render span.",
ImmutableMap.<String, AttributeValue>builder()
.put(
"SpanId",
AttributeValue.stringAttributeValue(
BaseEncoding.base16()
.lowerCase()
.encode(span.getContext().getSpanId().getBytes())))
.build());
emitSingleSpan(formatter, span);
}
out.write("</pre>\n");
} } | public class class_name {
private static void emitSpans(PrintWriter out, Formatter formatter, Collection<SpanData> spans) {
out.write("<pre>\n");
formatter.format("%-23s %18s%n", "When", "Elapsed(s)");
out.write("-------------------------------------------\n");
for (SpanData span : spans) {
tracer
.getCurrentSpan()
.addAnnotation(
"Render span.",
ImmutableMap.<String, AttributeValue>builder()
.put(
"SpanId",
AttributeValue.stringAttributeValue(
BaseEncoding.base16()
.lowerCase()
.encode(span.getContext().getSpanId().getBytes())))
.build()); // depends on control dependency: [for], data = [none]
emitSingleSpan(formatter, span); // depends on control dependency: [for], data = [span]
}
out.write("</pre>\n");
} } |
public class class_name {
public void setAnalysisSchemeNames(java.util.Collection<String> analysisSchemeNames) {
if (analysisSchemeNames == null) {
this.analysisSchemeNames = null;
return;
}
this.analysisSchemeNames = new com.amazonaws.internal.SdkInternalList<String>(analysisSchemeNames);
} } | public class class_name {
public void setAnalysisSchemeNames(java.util.Collection<String> analysisSchemeNames) {
if (analysisSchemeNames == null) {
this.analysisSchemeNames = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.analysisSchemeNames = new com.amazonaws.internal.SdkInternalList<String>(analysisSchemeNames);
} } |
public class class_name {
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void submit(PushApplication pushApplication, InternalUnifiedPushMessage message) {
logger.debug("Processing send request with '{}' payload", message.getMessage());
// collections for all the different variants:
final VariantMap variants = new VariantMap();
final List<String> variantIDs = message.getCriteria().getVariants();
// if the criteria payload did specify the "variants" field,
// we look up each of those mentioned variants, by their "variantID":
if (variantIDs != null) {
variantIDs.forEach(variantID -> {
Variant variant = genericVariantService.get().findByVariantID(variantID);
// does the variant exist ?
if (variant != null) {
variants.add(variant);
}
});
} else {
// No specific variants have been requested,
// we get all the variants, from the given PushApplicationEntity:
variants.addAll(pushApplication.getVariants());
}
// TODO: Not sure the transformation should be done here...
// There are likely better places to check if the metadata is way to long
String jsonMessageContent = message.toStrippedJsonString() ;
if (jsonMessageContent != null && jsonMessageContent.length() >= 4500) {
jsonMessageContent = message.toMinimizedJsonString();
}
final FlatPushMessageInformation pushMessageInformation =
metricsService.storeNewRequestFrom(
pushApplication.getPushApplicationID(),
jsonMessageContent,
message.getIpAddress(),
message.getClientIdentifier()
);
// we split the variants per type since each type may have its own configuration (e.g. batch size)
variants.forEach((variantType, variant) -> {
logger.info(String.format("Internal dispatching of push message for one %s variant (by %s)", variantType.getTypeName(), message.getClientIdentifier()));
dispatchVariantMessageEvent.fire(new MessageHolderWithVariants(pushMessageInformation, message, variantType, variant));
});
} } | public class class_name {
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void submit(PushApplication pushApplication, InternalUnifiedPushMessage message) {
logger.debug("Processing send request with '{}' payload", message.getMessage());
// collections for all the different variants:
final VariantMap variants = new VariantMap();
final List<String> variantIDs = message.getCriteria().getVariants();
// if the criteria payload did specify the "variants" field,
// we look up each of those mentioned variants, by their "variantID":
if (variantIDs != null) {
variantIDs.forEach(variantID -> {
Variant variant = genericVariantService.get().findByVariantID(variantID); // depends on control dependency: [if], data = [none]
// does the variant exist ?
if (variant != null) {
variants.add(variant); // depends on control dependency: [if], data = [(variant]
}
});
} else {
// No specific variants have been requested,
// we get all the variants, from the given PushApplicationEntity:
variants.addAll(pushApplication.getVariants());
}
// TODO: Not sure the transformation should be done here...
// There are likely better places to check if the metadata is way to long
String jsonMessageContent = message.toStrippedJsonString() ;
if (jsonMessageContent != null && jsonMessageContent.length() >= 4500) {
jsonMessageContent = message.toMinimizedJsonString();
}
final FlatPushMessageInformation pushMessageInformation =
metricsService.storeNewRequestFrom(
pushApplication.getPushApplicationID(),
jsonMessageContent,
message.getIpAddress(),
message.getClientIdentifier()
);
// we split the variants per type since each type may have its own configuration (e.g. batch size)
variants.forEach((variantType, variant) -> {
logger.info(String.format("Internal dispatching of push message for one %s variant (by %s)", variantType.getTypeName(), message.getClientIdentifier()));
dispatchVariantMessageEvent.fire(new MessageHolderWithVariants(pushMessageInformation, message, variantType, variant));
});
} } |
public class class_name {
protected boolean uploadDirectory(final String ftpServer, final String username, final String password,
final String sourceDirectoryPath, final String targetDirectoryPath) {
log.debug("FTP username: " + username);
try {
final FTPClient ftpClient = getFTPClient(ftpServer, username, password);
log.info(String.format(UPLOAD_DIR_START, sourceDirectoryPath, targetDirectoryPath));
uploadDirectory(ftpClient, sourceDirectoryPath, targetDirectoryPath, "");
log.info(String.format(UPLOAD_DIR_FINISH, sourceDirectoryPath, targetDirectoryPath));
ftpClient.disconnect();
return true;
} catch (Exception e) {
log.debug(e);
log.error(String.format(UPLOAD_DIR_FAILURE, sourceDirectoryPath, targetDirectoryPath));
}
return false;
} } | public class class_name {
protected boolean uploadDirectory(final String ftpServer, final String username, final String password,
final String sourceDirectoryPath, final String targetDirectoryPath) {
log.debug("FTP username: " + username);
try {
final FTPClient ftpClient = getFTPClient(ftpServer, username, password);
log.info(String.format(UPLOAD_DIR_START, sourceDirectoryPath, targetDirectoryPath)); // depends on control dependency: [try], data = [none]
uploadDirectory(ftpClient, sourceDirectoryPath, targetDirectoryPath, ""); // depends on control dependency: [try], data = [none]
log.info(String.format(UPLOAD_DIR_FINISH, sourceDirectoryPath, targetDirectoryPath)); // depends on control dependency: [try], data = [none]
ftpClient.disconnect(); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} catch (Exception e) {
log.debug(e);
log.error(String.format(UPLOAD_DIR_FAILURE, sourceDirectoryPath, targetDirectoryPath));
} // depends on control dependency: [catch], data = [none]
return false;
} } |
public class class_name {
public void setKeyguardLocked(boolean isKeyguardLocked) {
this.isKeyguardLocked = isKeyguardLocked;
if (callback != null) {
if (isKeyguardLocked) {
callback.onDismissCancelled();
} else {
callback.onDismissSucceeded();
}
callback = null;
}
} } | public class class_name {
public void setKeyguardLocked(boolean isKeyguardLocked) {
this.isKeyguardLocked = isKeyguardLocked;
if (callback != null) {
if (isKeyguardLocked) {
callback.onDismissCancelled(); // depends on control dependency: [if], data = [none]
} else {
callback.onDismissSucceeded(); // depends on control dependency: [if], data = [none]
}
callback = null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings({ "deprecation", "rawtypes", "unchecked" })
public static void setInputs(final Operator<?> contract, final List<List<Operator>> inputs) {
if (contract instanceof GenericDataSinkBase) {
if (inputs.size() != 1) {
throw new IllegalArgumentException("wrong number of inputs");
}
((GenericDataSinkBase) contract).setInputs(inputs.get(0));
} else if (contract instanceof SingleInputOperator) {
if (inputs.size() != 1) {
throw new IllegalArgumentException("wrong number of inputs");
}
((SingleInputOperator) contract).setInputs(inputs.get(0));
} else if (contract instanceof DualInputOperator) {
if (inputs.size() != 2) {
throw new IllegalArgumentException("wrong number of inputs");
}
((DualInputOperator) contract).setFirstInputs(inputs.get(0));
((DualInputOperator) contract).setSecondInputs(inputs.get(1));
}
} } | public class class_name {
@SuppressWarnings({ "deprecation", "rawtypes", "unchecked" })
public static void setInputs(final Operator<?> contract, final List<List<Operator>> inputs) {
if (contract instanceof GenericDataSinkBase) {
if (inputs.size() != 1) {
throw new IllegalArgumentException("wrong number of inputs");
}
((GenericDataSinkBase) contract).setInputs(inputs.get(0)); // depends on control dependency: [if], data = [none]
} else if (contract instanceof SingleInputOperator) {
if (inputs.size() != 1) {
throw new IllegalArgumentException("wrong number of inputs");
}
((SingleInputOperator) contract).setInputs(inputs.get(0)); // depends on control dependency: [if], data = [none]
} else if (contract instanceof DualInputOperator) {
if (inputs.size() != 2) {
throw new IllegalArgumentException("wrong number of inputs");
}
((DualInputOperator) contract).setFirstInputs(inputs.get(0)); // depends on control dependency: [if], data = [none]
((DualInputOperator) contract).setSecondInputs(inputs.get(1)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public CommerceTierPriceEntry remove(Serializable primaryKey)
throws NoSuchTierPriceEntryException {
Session session = null;
try {
session = openSession();
CommerceTierPriceEntry commerceTierPriceEntry = (CommerceTierPriceEntry)session.get(CommerceTierPriceEntryImpl.class,
primaryKey);
if (commerceTierPriceEntry == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchTierPriceEntryException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(commerceTierPriceEntry);
}
catch (NoSuchTierPriceEntryException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
} } | public class class_name {
@Override
public CommerceTierPriceEntry remove(Serializable primaryKey)
throws NoSuchTierPriceEntryException {
Session session = null;
try {
session = openSession();
CommerceTierPriceEntry commerceTierPriceEntry = (CommerceTierPriceEntry)session.get(CommerceTierPriceEntryImpl.class,
primaryKey);
if (commerceTierPriceEntry == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey); // depends on control dependency: [if], data = [none]
}
throw new NoSuchTierPriceEntryException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(commerceTierPriceEntry);
}
catch (NoSuchTierPriceEntryException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
} } |
public class class_name {
@Override
public EClass getIfcCartesianPointList3D() {
if (ifcCartesianPointList3DEClass == null) {
ifcCartesianPointList3DEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(80);
}
return ifcCartesianPointList3DEClass;
} } | public class class_name {
@Override
public EClass getIfcCartesianPointList3D() {
if (ifcCartesianPointList3DEClass == null) {
ifcCartesianPointList3DEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(80);
// depends on control dependency: [if], data = [none]
}
return ifcCartesianPointList3DEClass;
} } |
public class class_name {
private void zInternalChangeSelectedDateProcedure(
LocalDate newDate, YearMonth oldYearMonthOrNull) {
LocalDate oldDate = displayedSelectedDate;
displayedSelectedDate = newDate;
for (CalendarListener calendarListener : calendarListeners) {
CalendarSelectionEvent dateSelectionEvent = new CalendarSelectionEvent(
this, newDate, oldDate);
calendarListener.selectedDateChanged(dateSelectionEvent);
}
drawCalendar(displayedYearMonth, oldYearMonthOrNull);
// Fire a change event for beans binding.
firePropertyChange("selectedDate", oldDate, newDate);
} } | public class class_name {
private void zInternalChangeSelectedDateProcedure(
LocalDate newDate, YearMonth oldYearMonthOrNull) {
LocalDate oldDate = displayedSelectedDate;
displayedSelectedDate = newDate;
for (CalendarListener calendarListener : calendarListeners) {
CalendarSelectionEvent dateSelectionEvent = new CalendarSelectionEvent(
this, newDate, oldDate);
calendarListener.selectedDateChanged(dateSelectionEvent); // depends on control dependency: [for], data = [calendarListener]
}
drawCalendar(displayedYearMonth, oldYearMonthOrNull);
// Fire a change event for beans binding.
firePropertyChange("selectedDate", oldDate, newDate);
} } |
public class class_name {
@Override
public Object hookPlainly(String exp, Map<String, ? extends Object> contextMap, LaContainer container, Class<?> resultType) {
final CastResolved resolved = castResolver.resolveCast(exp, resultType);
final String realExp;
final Class<?> realType;
if (resolved != null) {
realExp = resolved.getFilteredExp();
realType = resolved.getResolvedType();
} else {
realExp = exp.trim();
realType = resultType;
}
return doHookPlainly(realExp, contextMap, container, realType);
} } | public class class_name {
@Override
public Object hookPlainly(String exp, Map<String, ? extends Object> contextMap, LaContainer container, Class<?> resultType) {
final CastResolved resolved = castResolver.resolveCast(exp, resultType);
final String realExp;
final Class<?> realType;
if (resolved != null) {
realExp = resolved.getFilteredExp(); // depends on control dependency: [if], data = [none]
realType = resolved.getResolvedType(); // depends on control dependency: [if], data = [none]
} else {
realExp = exp.trim(); // depends on control dependency: [if], data = [none]
realType = resultType; // depends on control dependency: [if], data = [none]
}
return doHookPlainly(realExp, contextMap, container, realType);
} } |
public class class_name {
protected final long plaintextLength(AbstractPutObjectRequest request,
ObjectMetadata metadata) {
if (request.getFile() != null) {
return request.getFile().length();
} else if (request.getInputStream() != null
&& metadata.getRawMetadataValue(Headers.CONTENT_LENGTH) != null) {
return metadata.getContentLength();
}
return -1;
} } | public class class_name {
protected final long plaintextLength(AbstractPutObjectRequest request,
ObjectMetadata metadata) {
if (request.getFile() != null) {
return request.getFile().length(); // depends on control dependency: [if], data = [none]
} else if (request.getInputStream() != null
&& metadata.getRawMetadataValue(Headers.CONTENT_LENGTH) != null) {
return metadata.getContentLength(); // depends on control dependency: [if], data = [none]
}
return -1;
} } |
public class class_name {
protected void clientDestroyed (Bureau bureau)
{
log.info("Client destroyed, destroying all agents", "bureau", bureau);
// clean up any agents attached to this bureau
for (AgentObject agent : bureau.agentStates.keySet()) {
_omgr.destroyObject(agent.getOid());
}
bureau.agentStates.clear();
if (_bureaus.remove(bureau.bureauId) == null) {
log.info("Bureau not found to remove", "bureau", bureau);
}
} } | public class class_name {
protected void clientDestroyed (Bureau bureau)
{
log.info("Client destroyed, destroying all agents", "bureau", bureau);
// clean up any agents attached to this bureau
for (AgentObject agent : bureau.agentStates.keySet()) {
_omgr.destroyObject(agent.getOid()); // depends on control dependency: [for], data = [agent]
}
bureau.agentStates.clear();
if (_bureaus.remove(bureau.bureauId) == null) {
log.info("Bureau not found to remove", "bureau", bureau); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String getContentSpecChecksum(final String contentSpecString) {
final Matcher matcher = CS_CHECKSUM_PATTERN.matcher(contentSpecString);
if (matcher.find()) {
return matcher.group("Checksum");
}
return null;
} } | public class class_name {
public static String getContentSpecChecksum(final String contentSpecString) {
final Matcher matcher = CS_CHECKSUM_PATTERN.matcher(contentSpecString);
if (matcher.find()) {
return matcher.group("Checksum"); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Override
public Set<TypeK> keySet() {
return new AbstractSet<TypeK> () {
@Override public void clear ( ) { NonBlockingHashMap.this.clear ( ); }
@Override public int size ( ) { return NonBlockingHashMap.this.size ( ); }
@Override public boolean contains( Object k ) { return NonBlockingHashMap.this.containsKey(k); }
@Override public boolean remove ( Object k ) { return NonBlockingHashMap.this.remove (k) != null; }
@Override public Iterator<TypeK> iterator() { return new SnapshotK(); }
// This is an efficient implementation of toArray instead of the standard
// one. In particular it uses a smart iteration over the NBHM.
@Override public <T> T[] toArray(T[] a) {
Object[] kvs = raw_array();
// Estimate size of array; be prepared to see more or fewer elements
int sz = size();
T[] r = a.length >= sz ? a :
(T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), sz);
// Fast efficient element walk.
int j=0;
for( int i=0; i<len(kvs); i++ ) {
Object K = key(kvs,i);
Object V = Prime.unbox(val(kvs,i));
if( K != null && K != TOMBSTONE && V != null && V != TOMBSTONE ) {
if( j >= r.length ) {
int sz2 = (int)Math.min(Integer.MAX_VALUE-8,((long)j)<<1);
if( sz2<=r.length ) throw new OutOfMemoryError("Required array size too large");
r = Arrays.copyOf(r,sz2);
}
r[j++] = (T)K;
}
}
if( j <= a.length ) { // Fit in the original array?
if( a!=r ) System.arraycopy(r,0,a,0,j);
if( j<a.length ) r[j++]=null; // One final null not in the spec but in the default impl
return a; // Return the original
}
return Arrays.copyOf(r,j);
}
};
} } | public class class_name {
@Override
public Set<TypeK> keySet() {
return new AbstractSet<TypeK> () {
@Override public void clear ( ) { NonBlockingHashMap.this.clear ( ); }
@Override public int size ( ) { return NonBlockingHashMap.this.size ( ); }
@Override public boolean contains( Object k ) { return NonBlockingHashMap.this.containsKey(k); }
@Override public boolean remove ( Object k ) { return NonBlockingHashMap.this.remove (k) != null; }
@Override public Iterator<TypeK> iterator() { return new SnapshotK(); }
// This is an efficient implementation of toArray instead of the standard
// one. In particular it uses a smart iteration over the NBHM.
@Override public <T> T[] toArray(T[] a) {
Object[] kvs = raw_array();
// Estimate size of array; be prepared to see more or fewer elements
int sz = size();
T[] r = a.length >= sz ? a :
(T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), sz);
// Fast efficient element walk.
int j=0;
for( int i=0; i<len(kvs); i++ ) {
Object K = key(kvs,i);
Object V = Prime.unbox(val(kvs,i));
if( K != null && K != TOMBSTONE && V != null && V != TOMBSTONE ) {
if( j >= r.length ) {
int sz2 = (int)Math.min(Integer.MAX_VALUE-8,((long)j)<<1);
if( sz2<=r.length ) throw new OutOfMemoryError("Required array size too large");
r = Arrays.copyOf(r,sz2); // depends on control dependency: [if], data = [none]
}
r[j++] = (T)K; // depends on control dependency: [if], data = [none]
}
}
if( j <= a.length ) { // Fit in the original array?
if( a!=r ) System.arraycopy(r,0,a,0,j);
if( j<a.length ) r[j++]=null; // One final null not in the spec but in the default impl
return a; // Return the original // depends on control dependency: [if], data = [none]
}
return Arrays.copyOf(r,j);
}
};
} } |
public class class_name {
private Entity<? extends Serializable> onBeforeSave(
Entity<? extends Serializable> entity) {
Class<?> cls = entity.getClass();
String indexName = DaoHelper.getExtendFieldName(cls, ExtendField.Index);
String pathName = DaoHelper.getExtendFieldName(cls, ExtendField.Path);
String parentName = DaoHelper.getExtendFieldName(cls,
ExtendField.Parent);
// 可记录时间的
if (Dateable.class.isAssignableFrom(cls)) {
Date now = Calendar.getInstance().getTime();
((Dateable) entity).setCreateDate(now);
((Dateable) entity).setLastModifiedDate(now);
}
// 可树形结构化的
if (Treeable.class.isAssignableFrom(cls)) {
Treeable self = ((Treeable) entity);
// 获取上级节点
Serializable parentId = self.getParent();
// 设置节点自身的路径
if (isNull(parentId)) {
self.setPath("/"); // 没有上级节点的节点
// 设置节点自身的排位
Object maxIndex = createCriteria(cls)
.add(Restrictions.eq(pathName, "/"))
.setProjection(Projections.max(indexName))
.uniqueResult();
self.setIndex(isNull(maxIndex) ? 1 : Integer.valueOf(maxIndex
.toString()) + 1);
} else {
// 设置节点自身的排位
Object maxIndex = createCriteria(cls)
.add(Restrictions.eq(parentName, parentId))
.setProjection(Projections.max(indexName))
.uniqueResult();
self.setIndex(isNull(maxIndex) ? 1 : Integer.valueOf(maxIndex
.toString()) + 1);
}
}
// 可移动的
else if (Movable.class.isAssignableFrom(cls)) {
// 设置自身的排位
Integer maxIndex = 1;
Object maxVal = createCriteria(cls).setProjection(
Projections.max(indexName)).uniqueResult();
if (notNull(maxVal)) {
maxIndex = Integer.valueOf(maxVal.toString()) + 1;
}
((Movable) entity).setIndex(maxIndex);
}
return entity;
} } | public class class_name {
private Entity<? extends Serializable> onBeforeSave(
Entity<? extends Serializable> entity) {
Class<?> cls = entity.getClass();
String indexName = DaoHelper.getExtendFieldName(cls, ExtendField.Index);
String pathName = DaoHelper.getExtendFieldName(cls, ExtendField.Path);
String parentName = DaoHelper.getExtendFieldName(cls,
ExtendField.Parent);
// 可记录时间的
if (Dateable.class.isAssignableFrom(cls)) {
Date now = Calendar.getInstance().getTime();
((Dateable) entity).setCreateDate(now);
// depends on control dependency: [if], data = [none]
((Dateable) entity).setLastModifiedDate(now);
// depends on control dependency: [if], data = [none]
}
// 可树形结构化的
if (Treeable.class.isAssignableFrom(cls)) {
Treeable self = ((Treeable) entity);
// 获取上级节点
Serializable parentId = self.getParent();
// 设置节点自身的路径
if (isNull(parentId)) {
self.setPath("/"); // 没有上级节点的节点
// depends on control dependency: [if], data = [none]
// 设置节点自身的排位
Object maxIndex = createCriteria(cls)
.add(Restrictions.eq(pathName, "/"))
.setProjection(Projections.max(indexName))
.uniqueResult();
self.setIndex(isNull(maxIndex) ? 1 : Integer.valueOf(maxIndex
.toString()) + 1);
// depends on control dependency: [if], data = [none]
} else {
// 设置节点自身的排位
Object maxIndex = createCriteria(cls)
.add(Restrictions.eq(parentName, parentId))
.setProjection(Projections.max(indexName))
.uniqueResult();
self.setIndex(isNull(maxIndex) ? 1 : Integer.valueOf(maxIndex
.toString()) + 1);
// depends on control dependency: [if], data = [none]
}
}
// 可移动的
else if (Movable.class.isAssignableFrom(cls)) {
// 设置自身的排位
Integer maxIndex = 1;
Object maxVal = createCriteria(cls).setProjection(
Projections.max(indexName)).uniqueResult();
if (notNull(maxVal)) {
maxIndex = Integer.valueOf(maxVal.toString()) + 1;
// depends on control dependency: [if], data = [none]
}
((Movable) entity).setIndex(maxIndex);
// depends on control dependency: [if], data = [none]
}
return entity;
} } |
public class class_name {
public String getDrl() {
StringBuffer sb = new StringBuffer();
for ( String rule : rules ) {
sb.append( rule ).append( "\n" );
}
return sb.toString();
} } | public class class_name {
public String getDrl() {
StringBuffer sb = new StringBuffer();
for ( String rule : rules ) {
sb.append( rule ).append( "\n" ); // depends on control dependency: [for], data = [rule]
}
return sb.toString();
} } |
public class class_name {
public void registerOnViewReadyListener(Runnable action) {
if (onViewReadyListeners == null) {
onViewReadyListeners = new CopyOnWriteArrayList<>();
}
onViewReadyListeners.add(action);
} } | public class class_name {
public void registerOnViewReadyListener(Runnable action) {
if (onViewReadyListeners == null) {
onViewReadyListeners = new CopyOnWriteArrayList<>(); // depends on control dependency: [if], data = [none]
}
onViewReadyListeners.add(action);
} } |
public class class_name {
public void setDataFormat(final String settingPattern, final String defaultPattern,
final CellFormatter cellFormatter) {
String currentPattern = POIUtils.getCellFormatPattern(cell, cellFormatter);
if(Utils.isNotEmpty(settingPattern)) {
// アノテーションで書式が指定されている場合、更新する
setDataFormat(settingPattern, cellFormatter);
} else if(currentPattern.isEmpty() || currentPattern.equalsIgnoreCase("general")) {
// セルの書式が設定されていない場合、デフォルトの値で更新する
setDataFormat(defaultPattern, cellFormatter);
}
} } | public class class_name {
public void setDataFormat(final String settingPattern, final String defaultPattern,
final CellFormatter cellFormatter) {
String currentPattern = POIUtils.getCellFormatPattern(cell, cellFormatter);
if(Utils.isNotEmpty(settingPattern)) {
// アノテーションで書式が指定されている場合、更新する
setDataFormat(settingPattern, cellFormatter);
// depends on control dependency: [if], data = [none]
} else if(currentPattern.isEmpty() || currentPattern.equalsIgnoreCase("general")) {
// セルの書式が設定されていない場合、デフォルトの値で更新する
setDataFormat(defaultPattern, cellFormatter);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected SortedSet<WeekDay> getWeekDays() {
SortedSet<WeekDay> result = new TreeSet<>();
for (CmsCheckBox box : m_checkboxes) {
if (box.isChecked()) {
result.add(WeekDay.valueOf(box.getInternalValue()));
}
}
return result;
} } | public class class_name {
protected SortedSet<WeekDay> getWeekDays() {
SortedSet<WeekDay> result = new TreeSet<>();
for (CmsCheckBox box : m_checkboxes) {
if (box.isChecked()) {
result.add(WeekDay.valueOf(box.getInternalValue()));
// depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
@Override
public void setTransition(Transition transition) {
if (anchor == null) {
if (transition != null) {
setUrl("#");
} else {
return;
}
}
if (anchor != null) JQMCommon.setTransition(anchor, transition);
} } | public class class_name {
@Override
public void setTransition(Transition transition) {
if (anchor == null) {
if (transition != null) {
setUrl("#"); // depends on control dependency: [if], data = [none]
} else {
return; // depends on control dependency: [if], data = [none]
}
}
if (anchor != null) JQMCommon.setTransition(anchor, transition);
} } |
public class class_name {
public static Object toBoolean(byte t_logical) {
if (t_logical == 'Y' || t_logical == 'y' || t_logical == 'T' || t_logical == 't') {
return Boolean.TRUE;
} else if (t_logical == 'N' || t_logical == 'n' || t_logical == 'F' || t_logical == 'f') {
return Boolean.FALSE;
}
return null;
} } | public class class_name {
public static Object toBoolean(byte t_logical) {
if (t_logical == 'Y' || t_logical == 'y' || t_logical == 'T' || t_logical == 't') {
return Boolean.TRUE; // depends on control dependency: [if], data = [none]
} else if (t_logical == 'N' || t_logical == 'n' || t_logical == 'F' || t_logical == 'f') {
return Boolean.FALSE; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public List<Map<String, INDArray>> output(MultiDataSetIterator iterator, String... outputs){
Preconditions.checkState(trainingConfig != null, "Training config has not been set");
List<String> reqVars;
if(outputs != null){
reqVars = Arrays.asList(outputs);
} else {
reqVars = outputs();
}
List<Map<String, INDArray>> predictions = new ArrayList<>();
if(!iterator.hasNext() && iterator.resetSupported())
iterator.reset();
while(iterator.hasNext()){
MultiDataSet ds = iterator.next();
Map<String,INDArray> placeholderMap = toPlaceholderMap(ds);
predictions.add(exec(placeholderMap, reqVars));
}
return predictions;
} } | public class class_name {
public List<Map<String, INDArray>> output(MultiDataSetIterator iterator, String... outputs){
Preconditions.checkState(trainingConfig != null, "Training config has not been set");
List<String> reqVars;
if(outputs != null){
reqVars = Arrays.asList(outputs); // depends on control dependency: [if], data = [(outputs]
} else {
reqVars = outputs(); // depends on control dependency: [if], data = [none]
}
List<Map<String, INDArray>> predictions = new ArrayList<>();
if(!iterator.hasNext() && iterator.resetSupported())
iterator.reset();
while(iterator.hasNext()){
MultiDataSet ds = iterator.next();
Map<String,INDArray> placeholderMap = toPlaceholderMap(ds);
predictions.add(exec(placeholderMap, reqVars)); // depends on control dependency: [while], data = [none]
}
return predictions;
} } |
public class class_name {
public int insert(String sql,Object[] params,String autoGeneratedColumnName)
throws DataAccessException{
//dynamic change catalog name
sql = changeCatalog(sql);
ReturnIdPreparedStatementCreator psc = new ReturnIdPreparedStatementCreator(sql, params, autoGeneratedColumnName);
KeyHolder keyHolder = new GeneratedKeyHolder();
try{
jdbcTemplate.update(psc, keyHolder);
}catch(DataAccessException e){
StringBuilder sb = new StringBuilder();
sb.append("[");
for(Object p:params){
sb.append(p + " | ");
}
sb.append("]");
logger.error("Error SQL: " + sql + " Params: " + sb.toString());
throw e;
}
return keyHolder.getKey().intValue();
} } | public class class_name {
public int insert(String sql,Object[] params,String autoGeneratedColumnName)
throws DataAccessException{
//dynamic change catalog name
sql = changeCatalog(sql);
ReturnIdPreparedStatementCreator psc = new ReturnIdPreparedStatementCreator(sql, params, autoGeneratedColumnName);
KeyHolder keyHolder = new GeneratedKeyHolder();
try{
jdbcTemplate.update(psc, keyHolder);
}catch(DataAccessException e){
StringBuilder sb = new StringBuilder();
sb.append("[");
for(Object p:params){
sb.append(p + " | "); // depends on control dependency: [for], data = [p]
}
sb.append("]");
logger.error("Error SQL: " + sql + " Params: " + sb.toString());
throw e;
}
return keyHolder.getKey().intValue();
} } |
public class class_name {
private static String unescape( String str, String encoding )
{
//We cannot unescape '+' to space because '+' is allowed in the file name
//str = str.replace('+', ' ');
//if the str does not contain "%", we don't need to do anything
if ( str.indexOf( '%' ) < 0 )
{
return str;
}
if ( encoding == null || encoding.length() == 0 )
{
encoding = WLS_DEFAULT_ENCODING;
}
// Do not assume String only contains ascii. str.length() <= str.getBytes().length
int out = 0;
byte[] strbytes = str.getBytes();
int len = strbytes.length;
boolean foundNonAscii = false;
for ( int in = 0; in < len; in++, out++ )
{
if ( strbytes[in] == '%' && ( in + 2 < len ) )
{
if ( Hex.isHexChar( strbytes[in + 1] ) &&
Hex.isHexChar( strbytes[in + 2] ) )
{
strbytes[out] =
( byte ) ( ( Hex.hexValueOf( strbytes[in + 1] ) << 4 ) +
( Hex.hexValueOf( strbytes[in + 2] ) << 0 ) );
in += 2;
continue;
}
}
// IE takes non-ASCII URLs. We use the default encoding
// if non-ASCII characters are contained in URLs.
if ( !foundNonAscii &&
( strbytes[in] <= 0x1f || strbytes[in] == 0x7f ) )
{
encoding = System.getProperty( "file.encoding" );
foundNonAscii = true;
}
strbytes[out] = strbytes[in];
}
return newString( strbytes, 0, out, encoding ); // was: BytesToString.newString(...)
} } | public class class_name {
private static String unescape( String str, String encoding )
{
//We cannot unescape '+' to space because '+' is allowed in the file name
//str = str.replace('+', ' ');
//if the str does not contain "%", we don't need to do anything
if ( str.indexOf( '%' ) < 0 )
{
return str; // depends on control dependency: [if], data = [none]
}
if ( encoding == null || encoding.length() == 0 )
{
encoding = WLS_DEFAULT_ENCODING; // depends on control dependency: [if], data = [none]
}
// Do not assume String only contains ascii. str.length() <= str.getBytes().length
int out = 0;
byte[] strbytes = str.getBytes();
int len = strbytes.length;
boolean foundNonAscii = false;
for ( int in = 0; in < len; in++, out++ )
{
if ( strbytes[in] == '%' && ( in + 2 < len ) )
{
if ( Hex.isHexChar( strbytes[in + 1] ) &&
Hex.isHexChar( strbytes[in + 2] ) )
{
strbytes[out] =
( byte ) ( ( Hex.hexValueOf( strbytes[in + 1] ) << 4 ) +
( Hex.hexValueOf( strbytes[in + 2] ) << 0 ) ); // depends on control dependency: [if], data = [none]
in += 2; // depends on control dependency: [if], data = [none]
continue;
}
}
// IE takes non-ASCII URLs. We use the default encoding
// if non-ASCII characters are contained in URLs.
if ( !foundNonAscii &&
( strbytes[in] <= 0x1f || strbytes[in] == 0x7f ) )
{
encoding = System.getProperty( "file.encoding" ); // depends on control dependency: [if], data = [none]
foundNonAscii = true; // depends on control dependency: [if], data = [none]
}
strbytes[out] = strbytes[in]; // depends on control dependency: [for], data = [in]
}
return newString( strbytes, 0, out, encoding ); // was: BytesToString.newString(...)
} } |
public class class_name {
public CmsPermissionSet getPermissionSet() {
CmsPermissionSetCustom pset = new CmsPermissionSetCustom();
CmsResource resource = getResource();
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_CONTROL, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_CONTROL);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_CONTROL);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(
resource,
CmsPermissionSet.ACCESS_DIRECT_PUBLISH,
false,
CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_DIRECT_PUBLISH);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_DIRECT_PUBLISH);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_READ, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_READ);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_READ);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_VIEW, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_VIEW);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_VIEW);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_WRITE);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_WRITE);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
return pset;
} } | public class class_name {
public CmsPermissionSet getPermissionSet() {
CmsPermissionSetCustom pset = new CmsPermissionSetCustom();
CmsResource resource = getResource();
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_CONTROL, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_CONTROL); // depends on control dependency: [if], data = [none]
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_CONTROL); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
} // depends on control dependency: [catch], data = [none]
try {
if (getCms().hasPermissions(
resource,
CmsPermissionSet.ACCESS_DIRECT_PUBLISH,
false,
CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_DIRECT_PUBLISH); // depends on control dependency: [if], data = [none]
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_DIRECT_PUBLISH); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
} // depends on control dependency: [catch], data = [none]
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_READ, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_READ); // depends on control dependency: [if], data = [none]
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_READ); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
} // depends on control dependency: [catch], data = [none]
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_VIEW, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_VIEW); // depends on control dependency: [if], data = [none]
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_VIEW); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
} // depends on control dependency: [catch], data = [none]
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_WRITE); // depends on control dependency: [if], data = [none]
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_WRITE); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
} // depends on control dependency: [catch], data = [none]
return pset;
} } |
public class class_name {
private void processRedirectResponse(Response response) throws RuntimeException, JSONException, MalformedURLException {
// a valid redirect response must contain the Location header.
ResponseImpl responseImpl = (ResponseImpl)response;
List<String> locationHeaders = responseImpl.getHeader(LOCATION_HEADER_NAME);
String location = (locationHeaders != null && locationHeaders.size() > 0) ? locationHeaders.get(0) : null;
if (location == null) {
throw new RuntimeException("Redirect response does not contain 'Location' header.");
}
// the redirect location url should contain "wl_result" value in query parameters.
URL url = new URL(location);
String query = url.getQuery();
if (query.contains(WL_RESULT)) {
String result = Utils.getParameterValueFromQuery(query, WL_RESULT);
JSONObject jsonResult = new JSONObject(result);
// process failures if any
JSONObject jsonFailures = jsonResult.optJSONObject(AUTH_FAILURE_VALUE_NAME);
if (jsonFailures != null) {
processFailures(jsonFailures);
listener.onFailure(response, null, null);
return;
}
// process successes if any
JSONObject jsonSuccesses = jsonResult.optJSONObject(AUTH_SUCCESS_VALUE_NAME);
if (jsonSuccesses != null) {
processSuccesses(jsonSuccesses);
}
}
// the rest is handles by the caller
listener.onSuccess(response);
} } | public class class_name {
private void processRedirectResponse(Response response) throws RuntimeException, JSONException, MalformedURLException {
// a valid redirect response must contain the Location header.
ResponseImpl responseImpl = (ResponseImpl)response;
List<String> locationHeaders = responseImpl.getHeader(LOCATION_HEADER_NAME);
String location = (locationHeaders != null && locationHeaders.size() > 0) ? locationHeaders.get(0) : null;
if (location == null) {
throw new RuntimeException("Redirect response does not contain 'Location' header.");
}
// the redirect location url should contain "wl_result" value in query parameters.
URL url = new URL(location);
String query = url.getQuery();
if (query.contains(WL_RESULT)) {
String result = Utils.getParameterValueFromQuery(query, WL_RESULT);
JSONObject jsonResult = new JSONObject(result);
// process failures if any
JSONObject jsonFailures = jsonResult.optJSONObject(AUTH_FAILURE_VALUE_NAME);
if (jsonFailures != null) {
processFailures(jsonFailures); // depends on control dependency: [if], data = [(jsonFailures]
listener.onFailure(response, null, null); // depends on control dependency: [if], data = [null)]
return; // depends on control dependency: [if], data = [none]
}
// process successes if any
JSONObject jsonSuccesses = jsonResult.optJSONObject(AUTH_SUCCESS_VALUE_NAME);
if (jsonSuccesses != null) {
processSuccesses(jsonSuccesses); // depends on control dependency: [if], data = [(jsonSuccesses]
}
}
// the rest is handles by the caller
listener.onSuccess(response);
} } |
public class class_name {
private Map<String, Map<String, String>> readSummaryFile(File outputFile) throws ExecutionException
{
List<String> algorithms = new ArrayList<String>();
Map<String, Map<String, String>> filesHashcodes = new HashMap<String, Map<String, String>>();
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(outputFile));
String line;
while ((line = reader.readLine()) != null)
{
// Read the CVS file header
if (isFileHeader(line))
{
readFileHeader(line, algorithms);
}
else
{
// Read the dependencies checksums
readDependenciesChecksums(line, algorithms, filesHashcodes);
}
}
}
catch (IOException e)
{
throw new ExecutionException(e.getMessage());
}
finally
{
IOUtil.close(reader);
}
return filesHashcodes;
} } | public class class_name {
private Map<String, Map<String, String>> readSummaryFile(File outputFile) throws ExecutionException
{
List<String> algorithms = new ArrayList<String>();
Map<String, Map<String, String>> filesHashcodes = new HashMap<String, Map<String, String>>();
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(outputFile));
String line;
while ((line = reader.readLine()) != null)
{
// Read the CVS file header
if (isFileHeader(line))
{
readFileHeader(line, algorithms); // depends on control dependency: [if], data = [none]
}
else
{
// Read the dependencies checksums
readDependenciesChecksums(line, algorithms, filesHashcodes); // depends on control dependency: [if], data = [none]
}
}
}
catch (IOException e)
{
throw new ExecutionException(e.getMessage());
}
finally
{
IOUtil.close(reader);
}
return filesHashcodes;
} } |
public class class_name {
public static String joinToString(CriteriaJoin criteriaJoin) {
StringBuilder builder = new StringBuilder("LEFT OUTER JOIN ")
.append(criteriaJoin.getEntityClass().getName())
.append(" ")
.append(criteriaJoin.getAlias())
.append(" ")
.append(" ON ");
if(criteriaJoin.getJoinRelations().size() == 0) {
throw new RuntimeException("Not found any Join Relations in " + criteriaJoin.getAlias() + " Join Criteria ! ");
}
StringJoiner joiner = new StringJoiner(" AND ");
List<JoinRelation> relationList = criteriaJoin.getJoinRelations();
for(JoinRelation joinRelation: relationList) {
StringBuilder relationBuilder = new StringBuilder("\n")
.append(joinRelation.getRelationCriteria().getAlias())
.append(".")
.append(joinRelation.getRelationField())
.append("=")
.append(joinRelation.getJoinedCriteria().getAlias())
.append(".")
.append(joinRelation.getJoinedField());
joiner.add(relationBuilder.toString());
}
if(joiner.length() > 0) {
builder.append(joiner.toString());
}
return builder.toString();
} } | public class class_name {
public static String joinToString(CriteriaJoin criteriaJoin) {
StringBuilder builder = new StringBuilder("LEFT OUTER JOIN ")
.append(criteriaJoin.getEntityClass().getName())
.append(" ")
.append(criteriaJoin.getAlias())
.append(" ")
.append(" ON ");
if(criteriaJoin.getJoinRelations().size() == 0) {
throw new RuntimeException("Not found any Join Relations in " + criteriaJoin.getAlias() + " Join Criteria ! ");
}
StringJoiner joiner = new StringJoiner(" AND ");
List<JoinRelation> relationList = criteriaJoin.getJoinRelations();
for(JoinRelation joinRelation: relationList) {
StringBuilder relationBuilder = new StringBuilder("\n")
.append(joinRelation.getRelationCriteria().getAlias())
.append(".")
.append(joinRelation.getRelationField())
.append("=")
.append(joinRelation.getJoinedCriteria().getAlias())
.append(".")
.append(joinRelation.getJoinedField());
joiner.add(relationBuilder.toString()); // depends on control dependency: [for], data = [none]
}
if(joiner.length() > 0) {
builder.append(joiner.toString()); // depends on control dependency: [if], data = [none]
}
return builder.toString();
} } |
public class class_name {
public static <T, P> int detectIndexWith(
Iterable<T> iterable,
Predicate2<? super T, ? super P> predicate,
P parameter)
{
if (iterable instanceof ArrayList<?>)
{
return ArrayListIterate.detectIndexWith((ArrayList<T>) iterable, predicate, parameter);
}
if (iterable instanceof List<?>)
{
return ListIterate.detectIndexWith((List<T>) iterable, predicate, parameter);
}
if (iterable != null)
{
return IterableIterate.detectIndexWith(iterable, predicate, parameter);
}
throw new IllegalArgumentException("Cannot perform detectIndexWith on null");
} } | public class class_name {
public static <T, P> int detectIndexWith(
Iterable<T> iterable,
Predicate2<? super T, ? super P> predicate,
P parameter)
{
if (iterable instanceof ArrayList<?>)
{
return ArrayListIterate.detectIndexWith((ArrayList<T>) iterable, predicate, parameter); // depends on control dependency: [if], data = [)]
}
if (iterable instanceof List<?>)
{
return ListIterate.detectIndexWith((List<T>) iterable, predicate, parameter); // depends on control dependency: [if], data = [)]
}
if (iterable != null)
{
return IterableIterate.detectIndexWith(iterable, predicate, parameter); // depends on control dependency: [if], data = [(iterable]
}
throw new IllegalArgumentException("Cannot perform detectIndexWith on null");
} } |
public class class_name {
public void replaceMessage(ValidationMessage messageToReplace, ValidationMessage replacementMessage) {
ValidationResults oldValidationResults = validationResults;
List newMessages = new ArrayList(oldValidationResults.getMessages());
final boolean containsMessageToReplace = validationResults.getMessages().contains(messageToReplace);
if (containsMessageToReplace) {
newMessages.remove(messageToReplace);
}
newMessages.add(replacementMessage);
validationResults = new DefaultValidationResults(newMessages);
fireChangedEvents();
if (containsMessageToReplace
&& !ObjectUtils.nullSafeEquals(messageToReplace.getProperty(), replacementMessage.getProperty())) {
fireValidationResultsChanged(messageToReplace.getProperty());
}
fireValidationResultsChanged(replacementMessage.getProperty());
} } | public class class_name {
public void replaceMessage(ValidationMessage messageToReplace, ValidationMessage replacementMessage) {
ValidationResults oldValidationResults = validationResults;
List newMessages = new ArrayList(oldValidationResults.getMessages());
final boolean containsMessageToReplace = validationResults.getMessages().contains(messageToReplace);
if (containsMessageToReplace) {
newMessages.remove(messageToReplace); // depends on control dependency: [if], data = [none]
}
newMessages.add(replacementMessage);
validationResults = new DefaultValidationResults(newMessages);
fireChangedEvents();
if (containsMessageToReplace
&& !ObjectUtils.nullSafeEquals(messageToReplace.getProperty(), replacementMessage.getProperty())) {
fireValidationResultsChanged(messageToReplace.getProperty()); // depends on control dependency: [if], data = [none]
}
fireValidationResultsChanged(replacementMessage.getProperty());
} } |
public class class_name {
void removeExportedKeys(Table toDrop) {
// toDrop.schema may be null because it is not registerd
Schema schema = (Schema) schemaMap.get(toDrop.getSchemaName().name);
for (int i = 0; i < schema.tableList.size(); i++) {
Table table = (Table) schema.tableList.get(i);
for (int j = table.constraintList.length - 1; j >= 0; j--) {
Table refTable = table.constraintList[j].getRef();
if (toDrop == refTable) {
table.removeConstraint(j);
}
}
}
} } | public class class_name {
void removeExportedKeys(Table toDrop) {
// toDrop.schema may be null because it is not registerd
Schema schema = (Schema) schemaMap.get(toDrop.getSchemaName().name);
for (int i = 0; i < schema.tableList.size(); i++) {
Table table = (Table) schema.tableList.get(i);
for (int j = table.constraintList.length - 1; j >= 0; j--) {
Table refTable = table.constraintList[j].getRef();
if (toDrop == refTable) {
table.removeConstraint(j); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public ReplicationGroup withNodeGroups(NodeGroup... nodeGroups) {
if (this.nodeGroups == null) {
setNodeGroups(new com.amazonaws.internal.SdkInternalList<NodeGroup>(nodeGroups.length));
}
for (NodeGroup ele : nodeGroups) {
this.nodeGroups.add(ele);
}
return this;
} } | public class class_name {
public ReplicationGroup withNodeGroups(NodeGroup... nodeGroups) {
if (this.nodeGroups == null) {
setNodeGroups(new com.amazonaws.internal.SdkInternalList<NodeGroup>(nodeGroups.length)); // depends on control dependency: [if], data = [none]
}
for (NodeGroup ele : nodeGroups) {
this.nodeGroups.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public JobKey getJobKeyById(QualifiedJobId jobId) throws IOException {
byte[] indexKey = jobIdConv.toBytes(jobId);
Get g = new Get(indexKey);
g.addColumn(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES);
Table historyByJobIdTable = null;
try {
historyByJobIdTable = hbaseConnection
.getTable(TableName.valueOf(Constants.HISTORY_BY_JOBID_TABLE));
Result r = historyByJobIdTable.get(g);
if (r != null && !r.isEmpty()) {
byte[] historyKey =
r.getValue(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES);
if (historyKey != null && historyKey.length > 0) {
return jobKeyConv.fromBytes(historyKey);
}
}
} finally {
if (historyByJobIdTable != null) {
historyByJobIdTable.close();
}
}
return null;
} } | public class class_name {
public JobKey getJobKeyById(QualifiedJobId jobId) throws IOException {
byte[] indexKey = jobIdConv.toBytes(jobId);
Get g = new Get(indexKey);
g.addColumn(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES);
Table historyByJobIdTable = null;
try {
historyByJobIdTable = hbaseConnection
.getTable(TableName.valueOf(Constants.HISTORY_BY_JOBID_TABLE));
Result r = historyByJobIdTable.get(g);
if (r != null && !r.isEmpty()) {
byte[] historyKey =
r.getValue(Constants.INFO_FAM_BYTES, Constants.ROWKEY_COL_BYTES);
if (historyKey != null && historyKey.length > 0) {
return jobKeyConv.fromBytes(historyKey); // depends on control dependency: [if], data = [(historyKey]
}
}
} finally {
if (historyByJobIdTable != null) {
historyByJobIdTable.close(); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public boolean parse(Context context, ProcPatternElement terminator) throws NestingException {
// Prepare a child context
Context child = new Context(context);
child.checkNesting();
StringBuilder target = new StringBuilder();
child.setTarget(target);
if (scope != null) {
child.setScope(scope);
}
child.setTerminator(terminator);
// Parse it
boolean parsed = child.getScope().process(child);
if (parsed) {
// If parsing success
if (transparent) {
child.mergeWithParent();
}
setAttribute(context, target);
return true;
} else {
return false;
}
} } | public class class_name {
public boolean parse(Context context, ProcPatternElement terminator) throws NestingException {
// Prepare a child context
Context child = new Context(context);
child.checkNesting();
StringBuilder target = new StringBuilder();
child.setTarget(target);
if (scope != null) {
child.setScope(scope);
}
child.setTerminator(terminator);
// Parse it
boolean parsed = child.getScope().process(child);
if (parsed) {
// If parsing success
if (transparent) {
child.mergeWithParent(); // depends on control dependency: [if], data = [none]
}
setAttribute(context, target);
return true;
} else {
return false;
}
} } |
public class class_name {
final void externalPush(ForkJoinTask<?> task) {
WorkQueue[] ws; WorkQueue q; int m;
int r = ThreadLocalRandomHelper.getProbe();
int rs = runState;
if ((ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
(q = ws[m & r & SQMASK]) != null && r != 0 && rs > 0 &&
U.compareAndSwapInt(q, QLOCK, 0, 1)) {
ForkJoinTask<?>[] a; int am, n, s;
if ((a = q.array) != null &&
(am = a.length - 1) > (n = (s = q.top) - q.base)) {
int j = ((am & s) << ASHIFT) + ABASE;
U.putOrderedObject(a, j, task);
U.putOrderedInt(q, QTOP, s + 1);
U.putIntVolatile(q, QLOCK, 0);
if (n <= 1)
signalWork(ws, q);
return;
}
U.compareAndSwapInt(q, QLOCK, 1, 0);
}
externalSubmit(task);
} } | public class class_name {
final void externalPush(ForkJoinTask<?> task) {
WorkQueue[] ws; WorkQueue q; int m;
int r = ThreadLocalRandomHelper.getProbe();
int rs = runState;
if ((ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
(q = ws[m & r & SQMASK]) != null && r != 0 && rs > 0 &&
U.compareAndSwapInt(q, QLOCK, 0, 1)) {
ForkJoinTask<?>[] a; int am, n, s;
if ((a = q.array) != null &&
(am = a.length - 1) > (n = (s = q.top) - q.base)) {
int j = ((am & s) << ASHIFT) + ABASE;
U.putOrderedObject(a, j, task); // depends on control dependency: [if], data = [none]
U.putOrderedInt(q, QTOP, s + 1); // depends on control dependency: [if], data = [none]
U.putIntVolatile(q, QLOCK, 0); // depends on control dependency: [if], data = [none]
if (n <= 1)
signalWork(ws, q);
return; // depends on control dependency: [if], data = [none]
}
U.compareAndSwapInt(q, QLOCK, 1, 0); // depends on control dependency: [if], data = [none]
}
externalSubmit(task);
} } |
public class class_name {
private final long getSlotValueAndOffset(int excWord, int index, int excOffset) {
long value;
if((excWord&EXC_DOUBLE_SLOTS)==0) {
excOffset+=slotOffset(excWord, index);
value=exceptions.charAt(excOffset);
} else {
excOffset+=2*slotOffset(excWord, index);
value=exceptions.charAt(excOffset++);
value=(value<<16)|exceptions.charAt(excOffset);
}
return value |((long)excOffset<<32);
} } | public class class_name {
private final long getSlotValueAndOffset(int excWord, int index, int excOffset) {
long value;
if((excWord&EXC_DOUBLE_SLOTS)==0) {
excOffset+=slotOffset(excWord, index); // depends on control dependency: [if], data = [none]
value=exceptions.charAt(excOffset); // depends on control dependency: [if], data = [none]
} else {
excOffset+=2*slotOffset(excWord, index); // depends on control dependency: [if], data = [none]
value=exceptions.charAt(excOffset++); // depends on control dependency: [if], data = [none]
value=(value<<16)|exceptions.charAt(excOffset); // depends on control dependency: [if], data = [none]
}
return value |((long)excOffset<<32);
} } |
public class class_name {
public java.util.List<String> getMessages() {
if (messages == null) {
messages = new com.amazonaws.internal.SdkInternalList<String>();
}
return messages;
} } | public class class_name {
public java.util.List<String> getMessages() {
if (messages == null) {
messages = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return messages;
} } |
public class class_name {
private String format(LogEvent event) {
JsonObject jsonEvent = new JsonObject();
jsonEvent.addProperty("v", 0);
jsonEvent.addProperty("level", BUNYAN_LEVEL.get(event.getLevel()));
jsonEvent.addProperty("levelStr", event.getLevel().toString());
jsonEvent.addProperty("name", event.getLoggerName());
try {
jsonEvent.addProperty("hostname", InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
jsonEvent.addProperty("hostname", "unkown");
}
jsonEvent.addProperty("pid", event.getThreadId());
jsonEvent.addProperty("time", formatAsIsoUTCDateTime(event.getTimeMillis()));
jsonEvent.addProperty("msg", event.getMessage().getFormattedMessage());
jsonEvent.addProperty("src", event.getSource().getClassName());
if (event.getLevel().isMoreSpecificThan(Level.WARN) && event.getThrown() != null) {
JsonObject jsonError = new JsonObject();
Throwable e = event.getThrown();
jsonError.addProperty("message", e.getMessage());
jsonError.addProperty("name", e.getClass().getSimpleName());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
jsonError.addProperty("stack", sw.toString());
jsonEvent.add("err", jsonError);
}
return GSON.toJson(jsonEvent) + "\n";
} } | public class class_name {
private String format(LogEvent event) {
JsonObject jsonEvent = new JsonObject();
jsonEvent.addProperty("v", 0);
jsonEvent.addProperty("level", BUNYAN_LEVEL.get(event.getLevel()));
jsonEvent.addProperty("levelStr", event.getLevel().toString());
jsonEvent.addProperty("name", event.getLoggerName());
try {
jsonEvent.addProperty("hostname", InetAddress.getLocalHost().getHostName()); // depends on control dependency: [try], data = [none]
} catch (UnknownHostException e) {
jsonEvent.addProperty("hostname", "unkown");
} // depends on control dependency: [catch], data = [none]
jsonEvent.addProperty("pid", event.getThreadId());
jsonEvent.addProperty("time", formatAsIsoUTCDateTime(event.getTimeMillis()));
jsonEvent.addProperty("msg", event.getMessage().getFormattedMessage());
jsonEvent.addProperty("src", event.getSource().getClassName());
if (event.getLevel().isMoreSpecificThan(Level.WARN) && event.getThrown() != null) {
JsonObject jsonError = new JsonObject();
Throwable e = event.getThrown();
jsonError.addProperty("message", e.getMessage()); // depends on control dependency: [if], data = [none]
jsonError.addProperty("name", e.getClass().getSimpleName()); // depends on control dependency: [if], data = [none]
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw); // depends on control dependency: [if], data = [none]
jsonError.addProperty("stack", sw.toString()); // depends on control dependency: [if], data = [none]
jsonEvent.add("err", jsonError); // depends on control dependency: [if], data = [none]
}
return GSON.toJson(jsonEvent) + "\n";
} } |
public class class_name {
public void setRepositories( List<String> urls ) throws ProjectException {
List<Repository> repositories = new ArrayList<Repository>();
for ( String url : urls ) {
try {
Repository repository = RepoBuilder.repositoryFromUrl( url );
repositories.add( repository );
} catch (MalformedURLException e) {
throw new ProjectException( e );
}
}
getMavenModel().setRepositories( repositories);
} } | public class class_name {
public void setRepositories( List<String> urls ) throws ProjectException {
List<Repository> repositories = new ArrayList<Repository>();
for ( String url : urls ) {
try {
Repository repository = RepoBuilder.repositoryFromUrl( url );
repositories.add( repository ); // depends on control dependency: [try], data = [none]
} catch (MalformedURLException e) {
throw new ProjectException( e );
} // depends on control dependency: [catch], data = [none]
}
getMavenModel().setRepositories( repositories);
} } |
public class class_name {
public static Map<String, File[]> getVersionFilesByProdExtension(File installDir) {
Map<String, File[]> versionFiles = new TreeMap<String, File[]>();
Iterator<ProductExtensionInfo> productExtensions = ProductExtension.getProductExtensions().iterator();
while (productExtensions != null && productExtensions.hasNext()) {
ProductExtensionInfo prodExt = productExtensions.next();
String prodExtName = prodExt.getName();
if (0 != prodExtName.length()) {
String prodExtLocation = prodExt.getLocation();
if (prodExtLocation != null) {
String normalizedProdExtLoc = FileUtils.normalize(prodExtLocation);
if (FileUtils.pathIsAbsolute(normalizedProdExtLoc) == false) {
String parentPath = installDir.getParentFile().getAbsolutePath();
normalizedProdExtLoc = FileUtils.normalize(parentPath + "/" + prodExtLocation + "/");
}
File prodExtVersionDir = new File(normalizedProdExtLoc, VERSION_PROPERTY_DIRECTORY);
if (prodExtVersionDir.exists()) {
versionFiles.put(prodExtName, prodExtVersionDir.listFiles(versionFileFilter));
}
}
}
}
return versionFiles;
} } | public class class_name {
public static Map<String, File[]> getVersionFilesByProdExtension(File installDir) {
Map<String, File[]> versionFiles = new TreeMap<String, File[]>();
Iterator<ProductExtensionInfo> productExtensions = ProductExtension.getProductExtensions().iterator();
while (productExtensions != null && productExtensions.hasNext()) {
ProductExtensionInfo prodExt = productExtensions.next();
String prodExtName = prodExt.getName();
if (0 != prodExtName.length()) {
String prodExtLocation = prodExt.getLocation();
if (prodExtLocation != null) {
String normalizedProdExtLoc = FileUtils.normalize(prodExtLocation);
if (FileUtils.pathIsAbsolute(normalizedProdExtLoc) == false) {
String parentPath = installDir.getParentFile().getAbsolutePath();
normalizedProdExtLoc = FileUtils.normalize(parentPath + "/" + prodExtLocation + "/"); // depends on control dependency: [if], data = [none]
}
File prodExtVersionDir = new File(normalizedProdExtLoc, VERSION_PROPERTY_DIRECTORY);
if (prodExtVersionDir.exists()) {
versionFiles.put(prodExtName, prodExtVersionDir.listFiles(versionFileFilter)); // depends on control dependency: [if], data = [none]
}
}
}
}
return versionFiles;
} } |
public class class_name {
@Override
public Object getBean(String name) {
IocObject iocObject = pool.get(name);
if (iocObject == null) {
return null;
}
return iocObject.getObject();
} } | public class class_name {
@Override
public Object getBean(String name) {
IocObject iocObject = pool.get(name);
if (iocObject == null) {
return null; // depends on control dependency: [if], data = [none]
}
return iocObject.getObject();
} } |
public class class_name {
public static <E> void addInPlace(Counter<E> target, Counter<E> arg, double scale) {
for (E key : arg.keySet()) {
target.incrementCount(key, scale * arg.getCount(key));
}
} } | public class class_name {
public static <E> void addInPlace(Counter<E> target, Counter<E> arg, double scale) {
for (E key : arg.keySet()) {
target.incrementCount(key, scale * arg.getCount(key));
// depends on control dependency: [for], data = [key]
}
} } |
public class class_name {
public Job fork() {
init();
H2OCountedCompleter task = new H2OCountedCompleter() {
@Override public void compute2() {
try {
try {
// Exec always waits till the end of computation
Job.this.exec();
Job.this.remove();
} catch (Throwable t) {
if(!(t instanceof ExpectedExceptionForDebug))
Log.err(t);
Job.this.cancel(t);
}
} finally {
tryComplete();
}
}
};
start(task);
H2O.submitTask(task);
return this;
} } | public class class_name {
public Job fork() {
init();
H2OCountedCompleter task = new H2OCountedCompleter() {
@Override public void compute2() {
try {
try {
// Exec always waits till the end of computation
Job.this.exec(); // depends on control dependency: [try], data = [none]
Job.this.remove(); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
if(!(t instanceof ExpectedExceptionForDebug))
Log.err(t);
Job.this.cancel(t);
} // depends on control dependency: [catch], data = [none]
} finally {
tryComplete();
}
}
};
start(task);
H2O.submitTask(task);
return this;
} } |
public class class_name {
public int getUserID()
{
int iUserID = -1;
String strUserID = DBConstants.BLANK;
if (this.getRecord().getRecordOwner() != null)
if (this.getRecord().getRecordOwner().getTask() != null)
if (this.getRecord().getRecordOwner().getTask().getApplication() != null)
strUserID = ((BaseApplication)this.getRecord().getRecordOwner().getTask().getApplication()).getUserID();
try {
iUserID = Integer.parseInt(strUserID);
if (iUserID == 0)
iUserID = -1;
} catch (NumberFormatException e) {
iUserID = -1;
}
return iUserID;
} } | public class class_name {
public int getUserID()
{
int iUserID = -1;
String strUserID = DBConstants.BLANK;
if (this.getRecord().getRecordOwner() != null)
if (this.getRecord().getRecordOwner().getTask() != null)
if (this.getRecord().getRecordOwner().getTask().getApplication() != null)
strUserID = ((BaseApplication)this.getRecord().getRecordOwner().getTask().getApplication()).getUserID();
try {
iUserID = Integer.parseInt(strUserID); // depends on control dependency: [try], data = [none]
if (iUserID == 0)
iUserID = -1;
} catch (NumberFormatException e) {
iUserID = -1;
} // depends on control dependency: [catch], data = [none]
return iUserID;
} } |
public class class_name {
public int[] get() {
if (capacity < buffer.size()) {
capacity = buffer.size();
}
int[] res = buffer.toArray();
buffer.clear(capacity);
return res;
} } | public class class_name {
public int[] get() {
if (capacity < buffer.size()) {
capacity = buffer.size(); // depends on control dependency: [if], data = [none]
}
int[] res = buffer.toArray();
buffer.clear(capacity);
return res;
} } |
public class class_name {
private void copyObjectAndUpdateStats(int id, IndexInput in, Long inRef,
IndexOutput out) throws IOException {
int mtasId;
int objectFlags;
// read
in.seek(inRef);
mtasId = in.readVInt();
assert id == mtasId : "wrong id detected while copying object";
objectFlags = in.readVInt();
out.writeVInt(mtasId);
out.writeVInt(objectFlags);
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT) {
out.writeVInt(in.readVInt());
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE) {
int minPos = in.readVInt();
int maxPos = in.readVInt();
out.writeVInt(minPos);
out.writeVInt(maxPos);
tokenStatsAdd(minPos, maxPos);
} else if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET) {
int size = in.readVInt();
out.writeVInt(size);
SortedSet<Integer> list = new TreeSet<>();
int previousPosition = 0;
for (int t = 0; t < size; t++) {
int pos = in.readVInt();
out.writeVInt(pos);
previousPosition = (pos + previousPosition);
list.add(previousPosition);
}
assert list.size() == size : "duplicate positions in set are not allowed";
tokenStatsAdd(list.first(), list.last());
} else {
int pos = in.readVInt();
out.writeVInt(pos);
tokenStatsAdd(pos, pos);
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET) {
out.writeVInt(in.readVInt());
out.writeVInt(in.readVInt());
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET) {
out.writeVInt(in.readVInt());
out.writeVInt(in.readVInt());
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD) {
int length = in.readVInt();
out.writeVInt(length);
byte[] payload = new byte[length];
in.readBytes(payload, 0, length);
out.writeBytes(payload, payload.length);
}
out.writeVLong(in.readVLong());
} } | public class class_name {
private void copyObjectAndUpdateStats(int id, IndexInput in, Long inRef,
IndexOutput out) throws IOException {
int mtasId;
int objectFlags;
// read
in.seek(inRef);
mtasId = in.readVInt();
assert id == mtasId : "wrong id detected while copying object";
objectFlags = in.readVInt();
out.writeVInt(mtasId);
out.writeVInt(objectFlags);
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT) {
out.writeVInt(in.readVInt());
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE) {
int minPos = in.readVInt();
int maxPos = in.readVInt();
out.writeVInt(minPos);
out.writeVInt(maxPos);
tokenStatsAdd(minPos, maxPos);
} else if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET) {
int size = in.readVInt();
out.writeVInt(size);
SortedSet<Integer> list = new TreeSet<>();
int previousPosition = 0;
for (int t = 0; t < size; t++) {
int pos = in.readVInt();
out.writeVInt(pos); // depends on control dependency: [for], data = [none]
previousPosition = (pos + previousPosition); // depends on control dependency: [for], data = [none]
list.add(previousPosition); // depends on control dependency: [for], data = [none]
}
assert list.size() == size : "duplicate positions in set are not allowed";
tokenStatsAdd(list.first(), list.last());
} else {
int pos = in.readVInt();
out.writeVInt(pos);
tokenStatsAdd(pos, pos);
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET) {
out.writeVInt(in.readVInt());
out.writeVInt(in.readVInt());
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET) {
out.writeVInt(in.readVInt());
out.writeVInt(in.readVInt());
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD) {
int length = in.readVInt();
out.writeVInt(length);
byte[] payload = new byte[length];
in.readBytes(payload, 0, length);
out.writeBytes(payload, payload.length);
}
out.writeVLong(in.readVLong());
} } |
public class class_name {
public static String separatorsToSystem(String path) {
if (path == null) {
return null;
}
if (File.separatorChar == '\\') {
return separatorsToWindows(path);
}
return separatorsToUnix(path);
} } | public class class_name {
public static String separatorsToSystem(String path) {
if (path == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (File.separatorChar == '\\') {
return separatorsToWindows(path); // depends on control dependency: [if], data = [none]
}
return separatorsToUnix(path);
} } |
public class class_name {
public void onTimeEvent(final long timeNs, final long timesMs, final DriverConductor conductor)
{
switch (state)
{
case ACTIVE:
checkUntetheredSubscriptions(timeNs, conductor);
break;
case INACTIVE:
if (isDrained())
{
state = State.LINGER;
timeOfLastStateChangeNs = timeNs;
conductor.transitionToLinger(this);
}
isTrackingRebuild = false;
break;
case LINGER:
if ((timeOfLastStateChangeNs + imageLivenessTimeoutNs) - timeNs < 0)
{
state = State.DONE;
conductor.cleanupImage(this);
}
break;
}
} } | public class class_name {
public void onTimeEvent(final long timeNs, final long timesMs, final DriverConductor conductor)
{
switch (state)
{
case ACTIVE:
checkUntetheredSubscriptions(timeNs, conductor);
break;
case INACTIVE:
if (isDrained())
{
state = State.LINGER; // depends on control dependency: [if], data = [none]
timeOfLastStateChangeNs = timeNs; // depends on control dependency: [if], data = [none]
conductor.transitionToLinger(this); // depends on control dependency: [if], data = [none]
}
isTrackingRebuild = false;
break;
case LINGER:
if ((timeOfLastStateChangeNs + imageLivenessTimeoutNs) - timeNs < 0)
{
state = State.DONE; // depends on control dependency: [if], data = [none]
conductor.cleanupImage(this); // depends on control dependency: [if], data = [none]
}
break;
}
} } |
public class class_name {
private static void incrementImplHydrogenCount(final IAtom atom) {
Integer hCount = atom.getImplicitHydrogenCount();
if (hCount == null) {
if (!(atom instanceof IPseudoAtom))
throw new IllegalArgumentException("a non-pseudo atom had an unset hydrogen count");
hCount = 0;
}
atom.setImplicitHydrogenCount(hCount + 1);
} } | public class class_name {
private static void incrementImplHydrogenCount(final IAtom atom) {
Integer hCount = atom.getImplicitHydrogenCount();
if (hCount == null) {
if (!(atom instanceof IPseudoAtom))
throw new IllegalArgumentException("a non-pseudo atom had an unset hydrogen count");
hCount = 0; // depends on control dependency: [if], data = [none]
}
atom.setImplicitHydrogenCount(hCount + 1);
} } |
public class class_name {
@Override
public void play(SpeechAnnouncement speechAnnouncement) {
boolean isValidAnnouncement = speechAnnouncement != null
&& !TextUtils.isEmpty(speechAnnouncement.announcement());
boolean canPlay = isValidAnnouncement && languageSupported && !isMuted;
if (!canPlay) {
return;
}
fireInstructionListenerIfApi14();
HashMap<String, String> params = new HashMap<>(1);
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, DEFAULT_UTTERANCE_ID);
textToSpeech.speak(speechAnnouncement.announcement(), TextToSpeech.QUEUE_ADD, params);
} } | public class class_name {
@Override
public void play(SpeechAnnouncement speechAnnouncement) {
boolean isValidAnnouncement = speechAnnouncement != null
&& !TextUtils.isEmpty(speechAnnouncement.announcement());
boolean canPlay = isValidAnnouncement && languageSupported && !isMuted;
if (!canPlay) {
return; // depends on control dependency: [if], data = [none]
}
fireInstructionListenerIfApi14();
HashMap<String, String> params = new HashMap<>(1);
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, DEFAULT_UTTERANCE_ID);
textToSpeech.speak(speechAnnouncement.announcement(), TextToSpeech.QUEUE_ADD, params);
} } |
public class class_name {
static String parameterNameFor(CtBehavior method, LocalVariableAttribute locals, int i) {
if (locals == null) {
return Integer.toString(i + 1);
}
int modifiers = method.getModifiers();
int j = i;
if (Modifier.isSynchronized(modifiers)) {
// skip object to synchronize upon.
j++;
// System.err.println("Synchronized");
}
if (Modifier.isStatic(modifiers) == false) {
// skip "this"
j++;
// System.err.println("Instance");
}
String variableName = locals.variableName(j);
// if (variableName.equals("this")) {
// System.err.println("'this' returned as a parameter name for "
// + method.getName() + " index " + j
// +
// ", names are probably shifted. Please submit source for class in slf4j bugreport");
// }
return variableName;
} } | public class class_name {
static String parameterNameFor(CtBehavior method, LocalVariableAttribute locals, int i) {
if (locals == null) {
return Integer.toString(i + 1); // depends on control dependency: [if], data = [none]
}
int modifiers = method.getModifiers();
int j = i;
if (Modifier.isSynchronized(modifiers)) {
// skip object to synchronize upon.
j++; // depends on control dependency: [if], data = [none]
// System.err.println("Synchronized");
}
if (Modifier.isStatic(modifiers) == false) {
// skip "this"
j++; // depends on control dependency: [if], data = [none]
// System.err.println("Instance");
}
String variableName = locals.variableName(j);
// if (variableName.equals("this")) {
// System.err.println("'this' returned as a parameter name for "
// + method.getName() + " index " + j
// +
// ", names are probably shifted. Please submit source for class in slf4j bugreport");
// }
return variableName;
} } |
public class class_name {
@Override
public void run() {
try {
m_returned = m_method.invoke(m_object, m_args);
} catch (Throwable thrown) {
m_thrown = thrown;
}
} } | public class class_name {
@Override
public void run() {
try {
m_returned = m_method.invoke(m_object, m_args); // depends on control dependency: [try], data = [none]
} catch (Throwable thrown) {
m_thrown = thrown;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void record( final MethodDeclaration method,
final Node parentNode ) throws Exception {
final String name = method.getName().getFullyQualifiedName();
final Node methodNode = parentNode.addNode(name, ClassFileSequencerLexicon.METHOD);
methodNode.setProperty(ClassFileSequencerLexicon.NAME, name);
{ // javadocs
final Javadoc javadoc = method.getJavadoc();
if (javadoc != null) {
record(javadoc, methodNode);
}
}
{ // type parameters
@SuppressWarnings( "unchecked" )
final List<TypeParameter> typeParams = method.typeParameters();
if ((typeParams != null) && !typeParams.isEmpty()) {
final Node containerNode = methodNode.addNode(ClassFileSequencerLexicon.TYPE_PARAMETERS,
ClassFileSequencerLexicon.TYPE_PARAMETERS);
for (final TypeParameter param : typeParams) {
record(param, containerNode);
}
}
}
{ // modifiers
final int modifiers = method.getModifiers();
methodNode.setProperty(ClassFileSequencerLexicon.ABSTRACT, (modifiers & Modifier.ABSTRACT) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.FINAL, (modifiers & Modifier.FINAL) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.NATIVE, (modifiers & Modifier.NATIVE) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.STATIC, (modifiers & Modifier.STATIC) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.STRICT_FP, (modifiers & Modifier.STRICTFP) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.SYNCHRONIZED, (modifiers & Modifier.SYNCHRONIZED) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.VISIBILITY, getVisibility(modifiers));
}
{ // annotations
@SuppressWarnings( "unchecked" )
final List<IExtendedModifier> modifiers = method.modifiers();
recordAnnotations(modifiers, methodNode);
}
{ // parameters
@SuppressWarnings( "unchecked" )
final List<SingleVariableDeclaration> params = method.parameters();
if ((params != null) && !params.isEmpty()) {
final Node containerNode = methodNode.addNode(ClassFileSequencerLexicon.METHOD_PARAMETERS,
ClassFileSequencerLexicon.PARAMETERS);
for (final SingleVariableDeclaration param : params) {
record(param, containerNode);
}
}
}
{ // return type
if (method.isConstructor()) {
methodNode.setProperty(ClassFileSequencerLexicon.RETURN_TYPE_CLASS_NAME, Void.TYPE.getCanonicalName());
} else {
final Type returnType = method.getReturnType2();
methodNode.setProperty(ClassFileSequencerLexicon.RETURN_TYPE_CLASS_NAME, getTypeName(returnType));
record(returnType, ClassFileSequencerLexicon.RETURN_TYPE, methodNode);
}
}
{ // thrown exceptions
@SuppressWarnings( "unchecked" )
final List<Name> errors = method.thrownExceptions();
if ((errors != null) && !errors.isEmpty()) {
final String[] errorNames = new String[errors.size()];
int i = 0;
for (final Name error : errors) {
errorNames[i++] = error.getFullyQualifiedName();
}
methodNode.setProperty(ClassFileSequencerLexicon.THROWN_EXCEPTIONS, errorNames);
}
}
{ // body
final Block body = method.getBody();
if ((body != null) && (body.statements() != null) && !body.statements().isEmpty()) {
final Node bodyNode = methodNode.addNode(ClassFileSequencerLexicon.BODY, ClassFileSequencerLexicon.STATEMENTS);
record(body, bodyNode);
}
}
recordSourceReference(method, methodNode);
} } | public class class_name {
protected void record( final MethodDeclaration method,
final Node parentNode ) throws Exception {
final String name = method.getName().getFullyQualifiedName();
final Node methodNode = parentNode.addNode(name, ClassFileSequencerLexicon.METHOD);
methodNode.setProperty(ClassFileSequencerLexicon.NAME, name);
{ // javadocs
final Javadoc javadoc = method.getJavadoc();
if (javadoc != null) {
record(javadoc, methodNode); // depends on control dependency: [if], data = [(javadoc]
}
}
{ // type parameters
@SuppressWarnings( "unchecked" )
final List<TypeParameter> typeParams = method.typeParameters();
if ((typeParams != null) && !typeParams.isEmpty()) {
final Node containerNode = methodNode.addNode(ClassFileSequencerLexicon.TYPE_PARAMETERS,
ClassFileSequencerLexicon.TYPE_PARAMETERS);
for (final TypeParameter param : typeParams) {
record(param, containerNode); // depends on control dependency: [for], data = [param]
}
}
}
{ // modifiers
final int modifiers = method.getModifiers();
methodNode.setProperty(ClassFileSequencerLexicon.ABSTRACT, (modifiers & Modifier.ABSTRACT) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.FINAL, (modifiers & Modifier.FINAL) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.NATIVE, (modifiers & Modifier.NATIVE) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.STATIC, (modifiers & Modifier.STATIC) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.STRICT_FP, (modifiers & Modifier.STRICTFP) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.SYNCHRONIZED, (modifiers & Modifier.SYNCHRONIZED) != 0);
methodNode.setProperty(ClassFileSequencerLexicon.VISIBILITY, getVisibility(modifiers));
}
{ // annotations
@SuppressWarnings( "unchecked" )
final List<IExtendedModifier> modifiers = method.modifiers();
recordAnnotations(modifiers, methodNode);
}
{ // parameters
@SuppressWarnings( "unchecked" )
final List<SingleVariableDeclaration> params = method.parameters();
if ((params != null) && !params.isEmpty()) {
final Node containerNode = methodNode.addNode(ClassFileSequencerLexicon.METHOD_PARAMETERS,
ClassFileSequencerLexicon.PARAMETERS);
for (final SingleVariableDeclaration param : params) {
record(param, containerNode); // depends on control dependency: [for], data = [param]
}
}
}
{ // return type
if (method.isConstructor()) {
methodNode.setProperty(ClassFileSequencerLexicon.RETURN_TYPE_CLASS_NAME, Void.TYPE.getCanonicalName()); // depends on control dependency: [if], data = [none]
} else {
final Type returnType = method.getReturnType2();
methodNode.setProperty(ClassFileSequencerLexicon.RETURN_TYPE_CLASS_NAME, getTypeName(returnType)); // depends on control dependency: [if], data = [none]
record(returnType, ClassFileSequencerLexicon.RETURN_TYPE, methodNode); // depends on control dependency: [if], data = [none]
}
}
{ // thrown exceptions
@SuppressWarnings( "unchecked" )
final List<Name> errors = method.thrownExceptions();
if ((errors != null) && !errors.isEmpty()) {
final String[] errorNames = new String[errors.size()];
int i = 0;
for (final Name error : errors) {
errorNames[i++] = error.getFullyQualifiedName(); // depends on control dependency: [for], data = [error]
}
methodNode.setProperty(ClassFileSequencerLexicon.THROWN_EXCEPTIONS, errorNames); // depends on control dependency: [if], data = [none]
}
}
{ // body
final Block body = method.getBody();
if ((body != null) && (body.statements() != null) && !body.statements().isEmpty()) {
final Node bodyNode = methodNode.addNode(ClassFileSequencerLexicon.BODY, ClassFileSequencerLexicon.STATEMENTS);
record(body, bodyNode); // depends on control dependency: [if], data = [none]
}
}
recordSourceReference(method, methodNode);
} } |
public class class_name {
private static QName recurseUpToInferTypeRef(DMNModelImpl model, OutputClause originalElement, DMNElement recursionIdx) {
if ( recursionIdx.getParent() instanceof Decision ) {
InformationItem parentVariable = ((Decision) recursionIdx.getParent()).getVariable();
if ( parentVariable != null ) {
return variableTypeRefOrErrIfNull(model, parentVariable);
} else {
return null; // simply to avoid NPE, the proper error is already managed in compilation
}
} else if ( recursionIdx.getParent() instanceof BusinessKnowledgeModel ) {
InformationItem parentVariable = ((BusinessKnowledgeModel) recursionIdx.getParent()).getVariable();
if ( parentVariable != null ) {
return variableTypeRefOrErrIfNull(model, parentVariable);
} else {
return null; // simply to avoid NPE, the proper error is already managed in compilation
}
} else if ( recursionIdx.getParent() instanceof ContextEntry ) {
ContextEntry parentCtxEntry = (ContextEntry) recursionIdx.getParent();
if ( parentCtxEntry.getVariable() != null ) {
return variableTypeRefOrErrIfNull(model, parentCtxEntry.getVariable());
} else {
Context parentCtx = (Context) parentCtxEntry.getParent();
if ( parentCtx.getContextEntry().get(parentCtx.getContextEntry().size()-1).equals(parentCtxEntry) ) {
// the ContextEntry is the last one in the Context, so I can recurse up-ward in the DMN model tree
// please notice the recursion would be considering the parentCtxEntry's parent, which is the `parentCtx` so is effectively a 2x jump upward in the model tree
return recurseUpToInferTypeRef(model, originalElement, parentCtx);
} else {
// error not last ContextEntry in context
MsgUtil.reportMessage( logger,
DMNMessage.Severity.ERROR,
parentCtxEntry,
model,
null,
null,
Msg.MISSING_VARIABLE_ON_CONTEXT,
parentCtxEntry );
return null;
}
}
} else {
// this is only for safety in case the recursion is escaping the allowed path for a broken model.
MsgUtil.reportMessage( logger,
DMNMessage.Severity.ERROR,
originalElement,
model,
null,
null,
Msg.UNKNOWN_OUTPUT_TYPE_FOR_DT_ON_NODE,
originalElement.getParentDRDElement().getIdentifierString() );
return null;
}
} } | public class class_name {
private static QName recurseUpToInferTypeRef(DMNModelImpl model, OutputClause originalElement, DMNElement recursionIdx) {
if ( recursionIdx.getParent() instanceof Decision ) {
InformationItem parentVariable = ((Decision) recursionIdx.getParent()).getVariable();
if ( parentVariable != null ) {
return variableTypeRefOrErrIfNull(model, parentVariable); // depends on control dependency: [if], data = [none]
} else {
return null; // simply to avoid NPE, the proper error is already managed in compilation // depends on control dependency: [if], data = [none]
}
} else if ( recursionIdx.getParent() instanceof BusinessKnowledgeModel ) {
InformationItem parentVariable = ((BusinessKnowledgeModel) recursionIdx.getParent()).getVariable();
if ( parentVariable != null ) {
return variableTypeRefOrErrIfNull(model, parentVariable); // depends on control dependency: [if], data = [none]
} else {
return null; // simply to avoid NPE, the proper error is already managed in compilation // depends on control dependency: [if], data = [none]
}
} else if ( recursionIdx.getParent() instanceof ContextEntry ) {
ContextEntry parentCtxEntry = (ContextEntry) recursionIdx.getParent();
if ( parentCtxEntry.getVariable() != null ) {
return variableTypeRefOrErrIfNull(model, parentCtxEntry.getVariable()); // depends on control dependency: [if], data = [none]
} else {
Context parentCtx = (Context) parentCtxEntry.getParent();
if ( parentCtx.getContextEntry().get(parentCtx.getContextEntry().size()-1).equals(parentCtxEntry) ) {
// the ContextEntry is the last one in the Context, so I can recurse up-ward in the DMN model tree
// please notice the recursion would be considering the parentCtxEntry's parent, which is the `parentCtx` so is effectively a 2x jump upward in the model tree
return recurseUpToInferTypeRef(model, originalElement, parentCtx); // depends on control dependency: [if], data = [none]
} else {
// error not last ContextEntry in context
MsgUtil.reportMessage( logger,
DMNMessage.Severity.ERROR,
parentCtxEntry,
model,
null,
null,
Msg.MISSING_VARIABLE_ON_CONTEXT,
parentCtxEntry ); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
}
} else {
// this is only for safety in case the recursion is escaping the allowed path for a broken model.
MsgUtil.reportMessage( logger,
DMNMessage.Severity.ERROR,
originalElement,
model,
null,
null,
Msg.UNKNOWN_OUTPUT_TYPE_FOR_DT_ON_NODE,
originalElement.getParentDRDElement().getIdentifierString() ); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Nonnull
public AS2ClientResponse sendSynchronous () throws AS2ClientBuilderException
{
// Perform SMP client lookup
performSMPClientLookup ();
// Set derivable values
setDefaultDerivedValues ();
// Verify the whole data set
verifyContent ();
// Build message
// 1. read business document into memory - this may be a bottleneck!
Element aBusinessDocumentXML = null;
if (m_aBusinessDocumentRes != null)
{
final Document aXMLDocument = DOMReader.readXMLDOM (m_aBusinessDocumentRes);
if (aXMLDocument == null)
throw new AS2ClientBuilderException ("Failed to read business document '" +
m_aBusinessDocumentRes.getPath () +
"' as XML");
aBusinessDocumentXML = aXMLDocument.getDocumentElement ();
LOGGER.info ("Successfully parsed the business document");
}
else
{
aBusinessDocumentXML = m_aBusinessDocumentElement;
}
if (aBusinessDocumentXML == null)
throw new AS2ClientBuilderException ("No XML business content present!");
// 2. validate the business document
if (m_aVESID != null)
validateOutgoingBusinessDocument (aBusinessDocumentXML);
// 3. build PEPPOL SBDH data
final PeppolSBDHDocument aSBDHDoc = PeppolSBDHDocument.create (aBusinessDocumentXML,
PeppolIdentifierFactory.INSTANCE);
aSBDHDoc.setSenderWithDefaultScheme (m_aPeppolSenderID.getValue ());
aSBDHDoc.setReceiver (m_aPeppolReceiverID.getScheme (), m_aPeppolReceiverID.getValue ());
aSBDHDoc.setDocumentType (m_aPeppolDocumentTypeID.getScheme (), m_aPeppolDocumentTypeID.getValue ());
aSBDHDoc.setProcess (m_aPeppolProcessID.getScheme (), m_aPeppolProcessID.getValue ());
// 4. set client properties
// Start building the AS2 client settings
final AS2ClientSettings aAS2ClientSettings = new AS2ClientSettings ();
// Key store
aAS2ClientSettings.setKeyStore (m_aKeyStoreType, m_aKeyStoreFile, m_sKeyStorePassword);
aAS2ClientSettings.setSaveKeyStoreChangesToFile (m_bSaveKeyStoreChangesToFile);
// Fixed sender
aAS2ClientSettings.setSenderData (m_sSenderAS2ID, m_sSenderAS2Email, m_sSenderAS2KeyAlias);
// Dynamic receiver
aAS2ClientSettings.setReceiverData (m_sReceiverAS2ID, m_sReceiverAS2KeyAlias, m_sReceiverAS2Url);
aAS2ClientSettings.setReceiverCertificate (m_aReceiverCert);
// AS2 stuff - no need to change anything in this block
aAS2ClientSettings.setPartnershipName (aAS2ClientSettings.getSenderAS2ID () +
"-" +
aAS2ClientSettings.getReceiverAS2ID ());
aAS2ClientSettings.setMDNOptions (new DispositionOptions ().setMICAlg (m_eSigningAlgo)
.setMICAlgImportance (DispositionOptions.IMPORTANCE_REQUIRED)
.setProtocol (DispositionOptions.PROTOCOL_PKCS7_SIGNATURE)
.setProtocolImportance (DispositionOptions.IMPORTANCE_REQUIRED));
aAS2ClientSettings.setEncryptAndSign (null, m_eSigningAlgo);
aAS2ClientSettings.setMessageIDFormat (m_sMessageIDFormat);
aAS2ClientSettings.setConnectTimeoutMS (m_nConnectTimeoutMS);
aAS2ClientSettings.setReadTimeoutMS (m_nReadTimeoutMS);
// Add a custom header to request an MDN for IBM implementation
aAS2ClientSettings.customHeaders ().addHeader (CHttpHeader.DISPOSITION_NOTIFICATION_TO, "dummy");
final AS2ClientRequest aRequest = new AS2ClientRequest (m_sAS2Subject);
// 5. assemble and send
// Version with huge memory consumption
final StandardBusinessDocument aSBD = new PeppolSBDHDocumentWriter ().createStandardBusinessDocument (aSBDHDoc);
try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream ())
{
final SBDMarshaller aSBDMarshaller = new SBDMarshaller ();
// Set custom namespace context (work around an OpusCapita problem)
if (m_aNamespaceContext != null)
aSBDMarshaller.setNamespaceContext (m_aNamespaceContext);
else
{
// Ensure default marshaller without a prefix is used!
aSBDMarshaller.setNamespaceContext (new MapBasedNamespaceContext ().setDefaultNamespaceURI (CSBDH.SBDH_NS));
}
// Write to BAOS
if (aSBDMarshaller.write (aSBD, aBAOS).isFailure ())
throw new AS2ClientBuilderException ("Failed to serialize SBD!");
if (false)
{
// Use data to force
aRequest.setData (aBAOS.toByteArray ());
}
else
{
// Using a String is better when having a
// com.sun.xml.ws.encoding.XmlDataContentHandler installed!
aRequest.setData (aBAOS.getAsString (StandardCharsets.UTF_8), StandardCharsets.UTF_8);
}
// Explicitly add application/xml even though the "setData" may have
// suggested something else (like text/plain)
aRequest.setContentType (CMimeType.APPLICATION_XML.getAsString ());
// Set the custom content transfer encoding
aRequest.setContentTransferEncoding (m_eCTE);
}
final AS2Client aAS2Client = m_aAS2ClientFactory.get ();
if (false)
{
// Local Fiddler proxy
aAS2Client.setHttpProxy (new Proxy (Proxy.Type.HTTP, new InetSocketAddress ("127.0.0.1", 8888)));
}
final AS2ClientResponse aResponse = aAS2Client.sendSynchronous (aAS2ClientSettings, aRequest);
return aResponse;
} } | public class class_name {
@Nonnull
public AS2ClientResponse sendSynchronous () throws AS2ClientBuilderException
{
// Perform SMP client lookup
performSMPClientLookup ();
// Set derivable values
setDefaultDerivedValues ();
// Verify the whole data set
verifyContent ();
// Build message
// 1. read business document into memory - this may be a bottleneck!
Element aBusinessDocumentXML = null;
if (m_aBusinessDocumentRes != null)
{
final Document aXMLDocument = DOMReader.readXMLDOM (m_aBusinessDocumentRes);
if (aXMLDocument == null)
throw new AS2ClientBuilderException ("Failed to read business document '" +
m_aBusinessDocumentRes.getPath () +
"' as XML");
aBusinessDocumentXML = aXMLDocument.getDocumentElement ();
LOGGER.info ("Successfully parsed the business document");
}
else
{
aBusinessDocumentXML = m_aBusinessDocumentElement;
}
if (aBusinessDocumentXML == null)
throw new AS2ClientBuilderException ("No XML business content present!");
// 2. validate the business document
if (m_aVESID != null)
validateOutgoingBusinessDocument (aBusinessDocumentXML);
// 3. build PEPPOL SBDH data
final PeppolSBDHDocument aSBDHDoc = PeppolSBDHDocument.create (aBusinessDocumentXML,
PeppolIdentifierFactory.INSTANCE);
aSBDHDoc.setSenderWithDefaultScheme (m_aPeppolSenderID.getValue ());
aSBDHDoc.setReceiver (m_aPeppolReceiverID.getScheme (), m_aPeppolReceiverID.getValue ());
aSBDHDoc.setDocumentType (m_aPeppolDocumentTypeID.getScheme (), m_aPeppolDocumentTypeID.getValue ());
aSBDHDoc.setProcess (m_aPeppolProcessID.getScheme (), m_aPeppolProcessID.getValue ());
// 4. set client properties
// Start building the AS2 client settings
final AS2ClientSettings aAS2ClientSettings = new AS2ClientSettings ();
// Key store
aAS2ClientSettings.setKeyStore (m_aKeyStoreType, m_aKeyStoreFile, m_sKeyStorePassword);
aAS2ClientSettings.setSaveKeyStoreChangesToFile (m_bSaveKeyStoreChangesToFile);
// Fixed sender
aAS2ClientSettings.setSenderData (m_sSenderAS2ID, m_sSenderAS2Email, m_sSenderAS2KeyAlias);
// Dynamic receiver
aAS2ClientSettings.setReceiverData (m_sReceiverAS2ID, m_sReceiverAS2KeyAlias, m_sReceiverAS2Url);
aAS2ClientSettings.setReceiverCertificate (m_aReceiverCert);
// AS2 stuff - no need to change anything in this block
aAS2ClientSettings.setPartnershipName (aAS2ClientSettings.getSenderAS2ID () +
"-" +
aAS2ClientSettings.getReceiverAS2ID ());
aAS2ClientSettings.setMDNOptions (new DispositionOptions ().setMICAlg (m_eSigningAlgo)
.setMICAlgImportance (DispositionOptions.IMPORTANCE_REQUIRED)
.setProtocol (DispositionOptions.PROTOCOL_PKCS7_SIGNATURE)
.setProtocolImportance (DispositionOptions.IMPORTANCE_REQUIRED));
aAS2ClientSettings.setEncryptAndSign (null, m_eSigningAlgo);
aAS2ClientSettings.setMessageIDFormat (m_sMessageIDFormat);
aAS2ClientSettings.setConnectTimeoutMS (m_nConnectTimeoutMS);
aAS2ClientSettings.setReadTimeoutMS (m_nReadTimeoutMS);
// Add a custom header to request an MDN for IBM implementation
aAS2ClientSettings.customHeaders ().addHeader (CHttpHeader.DISPOSITION_NOTIFICATION_TO, "dummy");
final AS2ClientRequest aRequest = new AS2ClientRequest (m_sAS2Subject);
// 5. assemble and send
// Version with huge memory consumption
final StandardBusinessDocument aSBD = new PeppolSBDHDocumentWriter ().createStandardBusinessDocument (aSBDHDoc);
try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream ())
{
final SBDMarshaller aSBDMarshaller = new SBDMarshaller ();
// Set custom namespace context (work around an OpusCapita problem)
if (m_aNamespaceContext != null)
aSBDMarshaller.setNamespaceContext (m_aNamespaceContext);
else
{
// Ensure default marshaller without a prefix is used!
aSBDMarshaller.setNamespaceContext (new MapBasedNamespaceContext ().setDefaultNamespaceURI (CSBDH.SBDH_NS)); // depends on control dependency: [if], data = [none]
}
// Write to BAOS
if (aSBDMarshaller.write (aSBD, aBAOS).isFailure ())
throw new AS2ClientBuilderException ("Failed to serialize SBD!");
if (false)
{
// Use data to force
aRequest.setData (aBAOS.toByteArray ()); // depends on control dependency: [if], data = [none]
}
else
{
// Using a String is better when having a
// com.sun.xml.ws.encoding.XmlDataContentHandler installed!
aRequest.setData (aBAOS.getAsString (StandardCharsets.UTF_8), StandardCharsets.UTF_8); // depends on control dependency: [if], data = [none]
}
// Explicitly add application/xml even though the "setData" may have
// suggested something else (like text/plain)
aRequest.setContentType (CMimeType.APPLICATION_XML.getAsString ());
// Set the custom content transfer encoding
aRequest.setContentTransferEncoding (m_eCTE);
}
final AS2Client aAS2Client = m_aAS2ClientFactory.get ();
if (false)
{
// Local Fiddler proxy
aAS2Client.setHttpProxy (new Proxy (Proxy.Type.HTTP, new InetSocketAddress ("127.0.0.1", 8888)));
}
final AS2ClientResponse aResponse = aAS2Client.sendSynchronous (aAS2ClientSettings, aRequest);
return aResponse;
} } |
public class class_name {
private Iterable<Result<Upload>> listIncompleteUploads(final String bucketName, final String prefix,
final boolean recursive, final boolean aggregatePartSize) {
return new Iterable<Result<Upload>>() {
@Override
public Iterator<Result<Upload>> iterator() {
return new Iterator<Result<Upload>>() {
private String nextKeyMarker;
private String nextUploadIdMarker;
private ListMultipartUploadsResult listMultipartUploadsResult;
private Result<Upload> error;
private Iterator<Upload> uploadIterator;
private boolean completed = false;
private synchronized void populate() {
String delimiter = "/";
if (recursive) {
delimiter = null;
}
this.listMultipartUploadsResult = null;
this.uploadIterator = null;
try {
this.listMultipartUploadsResult = listIncompleteUploads(bucketName, nextKeyMarker, nextUploadIdMarker,
prefix, delimiter, 1000);
} catch (InvalidBucketNameException | NoSuchAlgorithmException | InsufficientDataException | IOException
| InvalidKeyException | NoResponseException | XmlPullParserException | ErrorResponseException
| InternalException e) {
this.error = new Result<>(null, e);
} finally {
if (this.listMultipartUploadsResult != null) {
this.uploadIterator = this.listMultipartUploadsResult.uploads().iterator();
} else {
this.uploadIterator = new LinkedList<Upload>().iterator();
}
}
}
private synchronized long getAggregatedPartSize(String objectName, String uploadId)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException {
long aggregatedPartSize = 0;
for (Result<Part> result : listObjectParts(bucketName, objectName, uploadId)) {
aggregatedPartSize += result.get().partSize();
}
return aggregatedPartSize;
}
@Override
public boolean hasNext() {
if (this.completed) {
return false;
}
if (this.error == null && this.uploadIterator == null) {
populate();
}
if (this.error == null && !this.uploadIterator.hasNext()
&& this.listMultipartUploadsResult.isTruncated()) {
this.nextKeyMarker = this.listMultipartUploadsResult.nextKeyMarker();
this.nextUploadIdMarker = this.listMultipartUploadsResult.nextUploadIdMarker();
populate();
}
if (this.error != null) {
return true;
}
if (this.uploadIterator.hasNext()) {
return true;
}
this.completed = true;
return false;
}
@Override
public Result<Upload> next() {
if (this.completed) {
throw new NoSuchElementException();
}
if (this.error == null && this.uploadIterator == null) {
populate();
}
if (this.error == null && !this.uploadIterator.hasNext()
&& this.listMultipartUploadsResult.isTruncated()) {
this.nextKeyMarker = this.listMultipartUploadsResult.nextKeyMarker();
this.nextUploadIdMarker = this.listMultipartUploadsResult.nextUploadIdMarker();
populate();
}
if (this.error != null) {
this.completed = true;
return this.error;
}
if (this.uploadIterator.hasNext()) {
Upload upload = this.uploadIterator.next();
if (aggregatePartSize) {
long aggregatedPartSize;
try {
aggregatedPartSize = getAggregatedPartSize(upload.objectName(), upload.uploadId());
} catch (InvalidBucketNameException | NoSuchAlgorithmException | InsufficientDataException | IOException
| InvalidKeyException | NoResponseException | XmlPullParserException | ErrorResponseException
| InternalException e) {
// special case: ignore the error as we can't propagate the exception in next()
aggregatedPartSize = -1;
}
upload.setAggregatedPartSize(aggregatedPartSize);
}
return new Result<>(upload, null);
}
this.completed = true;
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
} } | public class class_name {
private Iterable<Result<Upload>> listIncompleteUploads(final String bucketName, final String prefix,
final boolean recursive, final boolean aggregatePartSize) {
return new Iterable<Result<Upload>>() {
@Override
public Iterator<Result<Upload>> iterator() {
return new Iterator<Result<Upload>>() {
private String nextKeyMarker;
private String nextUploadIdMarker;
private ListMultipartUploadsResult listMultipartUploadsResult;
private Result<Upload> error;
private Iterator<Upload> uploadIterator;
private boolean completed = false;
private synchronized void populate() {
String delimiter = "/";
if (recursive) {
delimiter = null; // depends on control dependency: [if], data = [none]
}
this.listMultipartUploadsResult = null;
this.uploadIterator = null;
try {
this.listMultipartUploadsResult = listIncompleteUploads(bucketName, nextKeyMarker, nextUploadIdMarker,
prefix, delimiter, 1000); // depends on control dependency: [try], data = [none]
} catch (InvalidBucketNameException | NoSuchAlgorithmException | InsufficientDataException | IOException
| InvalidKeyException | NoResponseException | XmlPullParserException | ErrorResponseException
| InternalException e) {
this.error = new Result<>(null, e);
} finally { // depends on control dependency: [catch], data = [none]
if (this.listMultipartUploadsResult != null) {
this.uploadIterator = this.listMultipartUploadsResult.uploads().iterator(); // depends on control dependency: [if], data = [none]
} else {
this.uploadIterator = new LinkedList<Upload>().iterator(); // depends on control dependency: [if], data = [none]
}
}
}
private synchronized long getAggregatedPartSize(String objectName, String uploadId)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException {
long aggregatedPartSize = 0;
for (Result<Part> result : listObjectParts(bucketName, objectName, uploadId)) {
aggregatedPartSize += result.get().partSize();
}
return aggregatedPartSize;
}
@Override
public boolean hasNext() {
if (this.completed) {
return false; // depends on control dependency: [if], data = [none]
}
if (this.error == null && this.uploadIterator == null) {
populate(); // depends on control dependency: [if], data = [none]
}
if (this.error == null && !this.uploadIterator.hasNext()
&& this.listMultipartUploadsResult.isTruncated()) {
this.nextKeyMarker = this.listMultipartUploadsResult.nextKeyMarker(); // depends on control dependency: [if], data = [none]
this.nextUploadIdMarker = this.listMultipartUploadsResult.nextUploadIdMarker(); // depends on control dependency: [if], data = [none]
populate(); // depends on control dependency: [if], data = [none]
}
if (this.error != null) {
return true; // depends on control dependency: [if], data = [none]
}
if (this.uploadIterator.hasNext()) {
return true; // depends on control dependency: [if], data = [none]
}
this.completed = true;
return false;
}
@Override
public Result<Upload> next() {
if (this.completed) {
throw new NoSuchElementException();
}
if (this.error == null && this.uploadIterator == null) {
populate(); // depends on control dependency: [if], data = [none]
}
if (this.error == null && !this.uploadIterator.hasNext()
&& this.listMultipartUploadsResult.isTruncated()) {
this.nextKeyMarker = this.listMultipartUploadsResult.nextKeyMarker(); // depends on control dependency: [if], data = [none]
this.nextUploadIdMarker = this.listMultipartUploadsResult.nextUploadIdMarker(); // depends on control dependency: [if], data = [none]
populate(); // depends on control dependency: [if], data = [none]
}
if (this.error != null) {
this.completed = true; // depends on control dependency: [if], data = [none]
return this.error; // depends on control dependency: [if], data = [none]
}
if (this.uploadIterator.hasNext()) {
Upload upload = this.uploadIterator.next();
if (aggregatePartSize) {
long aggregatedPartSize;
try {
aggregatedPartSize = getAggregatedPartSize(upload.objectName(), upload.uploadId()); // depends on control dependency: [try], data = [none]
} catch (InvalidBucketNameException | NoSuchAlgorithmException | InsufficientDataException | IOException
| InvalidKeyException | NoResponseException | XmlPullParserException | ErrorResponseException
| InternalException e) {
// special case: ignore the error as we can't propagate the exception in next()
aggregatedPartSize = -1;
} // depends on control dependency: [catch], data = [none]
upload.setAggregatedPartSize(aggregatedPartSize); // depends on control dependency: [if], data = [none]
}
return new Result<>(upload, null); // depends on control dependency: [if], data = [none]
}
this.completed = true;
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
} } |
public class class_name {
private static ByteBuf append(ByteBufAllocator allocator, boolean useDirect,
X509Certificate cert, int count, ByteBuf pem) throws CertificateEncodingException {
ByteBuf encoded = Unpooled.wrappedBuffer(cert.getEncoded());
try {
ByteBuf base64 = SslUtils.toBase64(allocator, encoded);
try {
if (pem == null) {
// We try to approximate the buffer's initial size. The sizes of
// certificates can vary a lot so it'll be off a bit depending
// on the number of elements in the array (count argument).
pem = newBuffer(allocator, useDirect,
(BEGIN_CERT.length + base64.readableBytes() + END_CERT.length) * count);
}
pem.writeBytes(BEGIN_CERT);
pem.writeBytes(base64);
pem.writeBytes(END_CERT);
} finally {
base64.release();
}
} finally {
encoded.release();
}
return pem;
} } | public class class_name {
private static ByteBuf append(ByteBufAllocator allocator, boolean useDirect,
X509Certificate cert, int count, ByteBuf pem) throws CertificateEncodingException {
ByteBuf encoded = Unpooled.wrappedBuffer(cert.getEncoded());
try {
ByteBuf base64 = SslUtils.toBase64(allocator, encoded);
try {
if (pem == null) {
// We try to approximate the buffer's initial size. The sizes of
// certificates can vary a lot so it'll be off a bit depending
// on the number of elements in the array (count argument).
pem = newBuffer(allocator, useDirect,
(BEGIN_CERT.length + base64.readableBytes() + END_CERT.length) * count); // depends on control dependency: [if], data = [none]
}
pem.writeBytes(BEGIN_CERT); // depends on control dependency: [try], data = [none]
pem.writeBytes(base64); // depends on control dependency: [try], data = [none]
pem.writeBytes(END_CERT); // depends on control dependency: [try], data = [none]
} finally {
base64.release();
}
} finally {
encoded.release();
}
return pem;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.