code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private void showContactAsBarcode(Uri contactUri) { if (contactUri == null) { return; // Show error? } ContentResolver resolver = getContentResolver(); String id; String name; boolean hasPhone; try (Cursor cursor = resolver.query(contactUri, null, null, null, null)) { if (cursor == null || !cursor.moveToFirst()) { return; } id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID)); name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0; } // Don't require a name to be present, this contact might be just a phone number. Bundle bundle = new Bundle(); if (name != null && !name.isEmpty()) { bundle.putString(ContactsContract.Intents.Insert.NAME, massageContactData(name)); } if (hasPhone) { try (Cursor phonesCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + '=' + id, null, null)) { if (phonesCursor != null) { int foundPhone = 0; int phonesNumberColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); int phoneTypeColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); while (phonesCursor.moveToNext() && foundPhone < Contents.PHONE_KEYS.length) { String number = phonesCursor.getString(phonesNumberColumn); if (number != null && !number.isEmpty()) { bundle.putString(Contents.PHONE_KEYS[foundPhone], massageContactData(number)); } int type = phonesCursor.getInt(phoneTypeColumn); bundle.putInt(Contents.PHONE_TYPE_KEYS[foundPhone], type); foundPhone++; } } } } try (Cursor methodsCursor = resolver.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + '=' + id, null, null)) { if (methodsCursor != null && methodsCursor.moveToNext()) { String data = methodsCursor.getString( methodsCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS)); if (data != null && !data.isEmpty()) { bundle.putString(ContactsContract.Intents.Insert.POSTAL, massageContactData(data)); } } } try (Cursor emailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + '=' + id, null, null)) { if (emailCursor != null) { int foundEmail = 0; int emailColumn = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA); while (emailCursor.moveToNext() && foundEmail < Contents.EMAIL_KEYS.length) { String email = emailCursor.getString(emailColumn); if (email != null && !email.isEmpty()) { bundle.putString(Contents.EMAIL_KEYS[foundEmail], massageContactData(email)); } foundEmail++; } } } Intent intent = new Intent(Intents.Encode.ACTION); intent.addFlags(Intents.FLAG_NEW_DOC); intent.putExtra(Intents.Encode.TYPE, Contents.Type.CONTACT); intent.putExtra(Intents.Encode.DATA, bundle); intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString()); startActivity(intent); } }
public class class_name { private void showContactAsBarcode(Uri contactUri) { if (contactUri == null) { return; // Show error? // depends on control dependency: [if], data = [none] } ContentResolver resolver = getContentResolver(); String id; String name; boolean hasPhone; try (Cursor cursor = resolver.query(contactUri, null, null, null, null)) { if (cursor == null || !cursor.moveToFirst()) { return; // depends on control dependency: [if], data = [none] } id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID)); name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0; } // Don't require a name to be present, this contact might be just a phone number. Bundle bundle = new Bundle(); if (name != null && !name.isEmpty()) { bundle.putString(ContactsContract.Intents.Insert.NAME, massageContactData(name)); } if (hasPhone) { try (Cursor phonesCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + '=' + id, null, null)) { if (phonesCursor != null) { int foundPhone = 0; int phonesNumberColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); int phoneTypeColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); while (phonesCursor.moveToNext() && foundPhone < Contents.PHONE_KEYS.length) { String number = phonesCursor.getString(phonesNumberColumn); if (number != null && !number.isEmpty()) { bundle.putString(Contents.PHONE_KEYS[foundPhone], massageContactData(number)); // depends on control dependency: [if], data = [(number] } int type = phonesCursor.getInt(phoneTypeColumn); bundle.putInt(Contents.PHONE_TYPE_KEYS[foundPhone], type); // depends on control dependency: [while], data = [none] foundPhone++; // depends on control dependency: [while], data = [none] } } } } try (Cursor methodsCursor = resolver.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + '=' + id, null, null)) { if (methodsCursor != null && methodsCursor.moveToNext()) { String data = methodsCursor.getString( methodsCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS)); if (data != null && !data.isEmpty()) { bundle.putString(ContactsContract.Intents.Insert.POSTAL, massageContactData(data)); } } } try (Cursor emailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + '=' + id, null, null)) { if (emailCursor != null) { int foundEmail = 0; int emailColumn = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA); while (emailCursor.moveToNext() && foundEmail < Contents.EMAIL_KEYS.length) { String email = emailCursor.getString(emailColumn); if (email != null && !email.isEmpty()) { bundle.putString(Contents.EMAIL_KEYS[foundEmail], massageContactData(email)); } foundEmail++; } } } Intent intent = new Intent(Intents.Encode.ACTION); intent.addFlags(Intents.FLAG_NEW_DOC); intent.putExtra(Intents.Encode.TYPE, Contents.Type.CONTACT); intent.putExtra(Intents.Encode.DATA, bundle); intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString()); startActivity(intent); } }
public class class_name { public EClass getIfcServiceLifeFactor() { if (ifcServiceLifeFactorEClass == null) { ifcServiceLifeFactorEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(509); } return ifcServiceLifeFactorEClass; } }
public class class_name { public EClass getIfcServiceLifeFactor() { if (ifcServiceLifeFactorEClass == null) { ifcServiceLifeFactorEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(509); // depends on control dependency: [if], data = [none] } return ifcServiceLifeFactorEClass; } }
public class class_name { final ConnectionPoolConnection open(final long timeout, final TimeUnit timeoutUnit) throws InterruptedException { ConnectionPoolConnection conn = timeout >= 0 ? availableQueue.poll(timeout, timeoutUnit) : availableQueue.take(); if(conn != null) { if(!testOnLogicalOpen) { conn.logicalOpen(); conn.state.set(ConnectionPoolConnection.STATE_OPEN); } else { try { conn.logicalOpenWithTest(); conn.state.set(ConnectionPoolConnection.STATE_OPEN); } catch(SQLException se) { conn.state.set(ConnectionPoolConnection.STATE_REOPENING); stats.connectionErrors.mark(); reopen(conn); return open(); //Attempt to open another connection. } } } return conn; } }
public class class_name { final ConnectionPoolConnection open(final long timeout, final TimeUnit timeoutUnit) throws InterruptedException { ConnectionPoolConnection conn = timeout >= 0 ? availableQueue.poll(timeout, timeoutUnit) : availableQueue.take(); if(conn != null) { if(!testOnLogicalOpen) { conn.logicalOpen(); conn.state.set(ConnectionPoolConnection.STATE_OPEN); } else { try { conn.logicalOpenWithTest(); // depends on control dependency: [try], data = [none] conn.state.set(ConnectionPoolConnection.STATE_OPEN); // depends on control dependency: [try], data = [none] } catch(SQLException se) { conn.state.set(ConnectionPoolConnection.STATE_REOPENING); stats.connectionErrors.mark(); reopen(conn); return open(); //Attempt to open another connection. } // depends on control dependency: [catch], data = [none] } } return conn; } }
public class class_name { public boolean sendHtmlEmail(String toEmail, String title, String content) { LOG.info("send to " + toEmail); LOG.info("title: " + title); LOG.info("content" + content); if (StringUtils.isBlank(toEmail)) { return false; } String localName = ""; Visitor visitor = ThreadContext.getSessionVisitor(); if (visitor != null) { LOG.info(visitor.toString()); localName += visitor.getLoginUserName() + " "; } try { InetAddress addr = InetAddress.getLocalHost(); localName += addr.getHostName().toString(); } catch (UnknownHostException e) { LOG.warn("When send alarm mail,we can't get hostname", e); } String mailTitle = localName + "/" + getSystemDate(); int len = 0; int lenLimit = ALARM_MAIL_TITLE_LENGTH; if (title != null) { len = title.length(); if (len > lenLimit) { len = lenLimit; } mailTitle += title.substring(0, len); } String mailTo = toEmail; String mailFrom = emailProperties.getFromEmail(); String[] mailToList = mailTo.split(";"); if (content == null) { return false; } else { try { mailBean.sendHtmlMail(mailFrom, mailToList, mailTitle, content); } catch (Exception e) { LOG.error("When send alarm mail,we can't send it", e); return false; } } return true; } }
public class class_name { public boolean sendHtmlEmail(String toEmail, String title, String content) { LOG.info("send to " + toEmail); LOG.info("title: " + title); LOG.info("content" + content); if (StringUtils.isBlank(toEmail)) { return false; // depends on control dependency: [if], data = [none] } String localName = ""; Visitor visitor = ThreadContext.getSessionVisitor(); if (visitor != null) { LOG.info(visitor.toString()); // depends on control dependency: [if], data = [(visitor] localName += visitor.getLoginUserName() + " "; // depends on control dependency: [if], data = [none] } try { InetAddress addr = InetAddress.getLocalHost(); localName += addr.getHostName().toString(); // depends on control dependency: [try], data = [none] } catch (UnknownHostException e) { LOG.warn("When send alarm mail,we can't get hostname", e); } // depends on control dependency: [catch], data = [none] String mailTitle = localName + "/" + getSystemDate(); int len = 0; int lenLimit = ALARM_MAIL_TITLE_LENGTH; if (title != null) { len = title.length(); // depends on control dependency: [if], data = [none] if (len > lenLimit) { len = lenLimit; // depends on control dependency: [if], data = [none] } mailTitle += title.substring(0, len); // depends on control dependency: [if], data = [none] } String mailTo = toEmail; String mailFrom = emailProperties.getFromEmail(); String[] mailToList = mailTo.split(";"); if (content == null) { return false; // depends on control dependency: [if], data = [none] } else { try { mailBean.sendHtmlMail(mailFrom, mailToList, mailTitle, content); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOG.error("When send alarm mail,we can't send it", e); return false; } // depends on control dependency: [catch], data = [none] } return true; } }
public class class_name { @Override public InRequest newInRequest() { RequestHttp2 request = _freeRequest.allocate(); if (request == null) { request = new RequestHttp2(_httpProtocol); /* connTcp(), _httpContainer, this); */ } RequestBaratineImpl requestWeb = new RequestBaratineImpl(this, request); //OutChannelHttp2 stream = request.getStreamOut(); //stream.init(streamId, _outHttp); //request.init(this); // , _outHttp); return request; } }
public class class_name { @Override public InRequest newInRequest() { RequestHttp2 request = _freeRequest.allocate(); if (request == null) { request = new RequestHttp2(_httpProtocol); // depends on control dependency: [if], data = [none] /* connTcp(), _httpContainer, this); */ } RequestBaratineImpl requestWeb = new RequestBaratineImpl(this, request); //OutChannelHttp2 stream = request.getStreamOut(); //stream.init(streamId, _outHttp); //request.init(this); // , _outHttp); return request; } }
public class class_name { protected AccessDecisionManager accessDecisionManager() { List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList<AccessDecisionVoter<? extends Object>>(); ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice(); expressionAdvice.setExpressionHandler(getExpressionHandler()); if (prePostEnabled()) { decisionVoters .add(new PreInvocationAuthorizationAdviceVoter(expressionAdvice)); } if (jsr250Enabled()) { decisionVoters.add(new Jsr250Voter()); } RoleVoter roleVoter = new RoleVoter(); GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull(GrantedAuthorityDefaults.class); if (grantedAuthorityDefaults != null) { roleVoter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix()); } decisionVoters.add(roleVoter); decisionVoters.add(new AuthenticatedVoter()); return new AffirmativeBased(decisionVoters); } }
public class class_name { protected AccessDecisionManager accessDecisionManager() { List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList<AccessDecisionVoter<? extends Object>>(); ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice(); expressionAdvice.setExpressionHandler(getExpressionHandler()); if (prePostEnabled()) { decisionVoters .add(new PreInvocationAuthorizationAdviceVoter(expressionAdvice)); // depends on control dependency: [if], data = [none] } if (jsr250Enabled()) { decisionVoters.add(new Jsr250Voter()); // depends on control dependency: [if], data = [none] } RoleVoter roleVoter = new RoleVoter(); GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull(GrantedAuthorityDefaults.class); if (grantedAuthorityDefaults != null) { roleVoter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix()); // depends on control dependency: [if], data = [(grantedAuthorityDefaults] } decisionVoters.add(roleVoter); decisionVoters.add(new AuthenticatedVoter()); return new AffirmativeBased(decisionVoters); } }
public class class_name { private synchronized void setupResourceInfo(String name, Class<?> callersClass) { if (name == null) { return; } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } }
public class class_name { private synchronized void setupResourceInfo(String name, Class<?> callersClass) { if (name == null) { return; // depends on control dependency: [if], data = [none] } /* J2ObjC removed. setCallersClassLoaderRef(callersClass); */ if (findResourceBundle(name, true) == null) { // We've failed to find an expected ResourceBundle. // unset the caller's ClassLoader since we were unable to find the // the bundle using it this.callersClassLoaderRef = null; // depends on control dependency: [if], data = [none] throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } }
public class class_name { static public void dumpInfo(String file, PrintStream out, Configuration conf) throws IOException { final int maxKeySampleLen = 16; Path path = new Path(file); FileSystem fs = path.getFileSystem(conf); long length = fs.getFileStatus(path).getLen(); FSDataInputStream fsdis = fs.open(path); TFile.Reader reader = new TFile.Reader(fsdis, length, conf); try { LinkedHashMap<String, String> properties = new LinkedHashMap<String, String>(); int blockCnt = reader.readerBCF.getBlockCount(); int metaBlkCnt = reader.readerBCF.metaIndex.index.size(); properties.put("BCFile Version", reader.readerBCF.version.toString()); properties.put("TFile Version", reader.tfileMeta.version.toString()); properties.put("File Length", Long.toString(length)); properties.put("Data Compression", reader.readerBCF .getDefaultCompressionName()); properties.put("Record Count", Long.toString(reader.getEntryCount())); properties.put("Sorted", Boolean.toString(reader.isSorted())); if (reader.isSorted()) { properties.put("Comparator", reader.getComparatorName()); } properties.put("Data Block Count", Integer.toString(blockCnt)); long dataSize = 0, dataSizeUncompressed = 0; if (blockCnt > 0) { for (int i = 0; i < blockCnt; ++i) { BlockRegion region = reader.readerBCF.dataIndex.getBlockRegionList().get(i); dataSize += region.getCompressedSize(); dataSizeUncompressed += region.getRawSize(); } properties.put("Data Block Bytes", Long.toString(dataSize)); if (reader.readerBCF.getDefaultCompressionName() != "none") { properties.put("Data Block Uncompressed Bytes", Long .toString(dataSizeUncompressed)); properties.put("Data Block Compression Ratio", String.format( "1:%.1f", (double) dataSizeUncompressed / dataSize)); } } properties.put("Meta Block Count", Integer.toString(metaBlkCnt)); long metaSize = 0, metaSizeUncompressed = 0; if (metaBlkCnt > 0) { Collection<MetaIndexEntry> metaBlks = reader.readerBCF.metaIndex.index.values(); boolean calculateCompression = false; for (Iterator<MetaIndexEntry> it = metaBlks.iterator(); it.hasNext();) { MetaIndexEntry e = it.next(); metaSize += e.getRegion().getCompressedSize(); metaSizeUncompressed += e.getRegion().getRawSize(); if (e.getCompressionAlgorithm() != Compression.Algorithm.NONE) { calculateCompression = true; } } properties.put("Meta Block Bytes", Long.toString(metaSize)); if (calculateCompression) { properties.put("Meta Block Uncompressed Bytes", Long .toString(metaSizeUncompressed)); properties.put("Meta Block Compression Ratio", String.format( "1:%.1f", (double) metaSizeUncompressed / metaSize)); } } properties.put("Meta-Data Size Ratio", String.format("1:%.1f", (double) dataSize / metaSize)); long leftOverBytes = length - dataSize - metaSize; long miscSize = BCFile.Magic.size() * 2 + Long.SIZE / Byte.SIZE + Version.size(); long metaIndexSize = leftOverBytes - miscSize; properties.put("Meta Block Index Bytes", Long.toString(metaIndexSize)); properties.put("Headers Etc Bytes", Long.toString(miscSize)); // Now output the properties table. int maxKeyLength = 0; Set<Map.Entry<String, String>> entrySet = properties.entrySet(); for (Iterator<Map.Entry<String, String>> it = entrySet.iterator(); it .hasNext();) { Map.Entry<String, String> e = it.next(); if (e.getKey().length() > maxKeyLength) { maxKeyLength = e.getKey().length(); } } for (Iterator<Map.Entry<String, String>> it = entrySet.iterator(); it .hasNext();) { Map.Entry<String, String> e = it.next(); out.printf("%s : %s\n", Align.format(e.getKey(), maxKeyLength, Align.LEFT), e.getValue()); } out.println(); reader.checkTFileDataIndex(); if (blockCnt > 0) { String blkID = "Data-Block"; int blkIDWidth = Align.calculateWidth(blkID, blockCnt); int blkIDWidth2 = Align.calculateWidth("", blockCnt); String offset = "Offset"; int offsetWidth = Align.calculateWidth(offset, length); String blkLen = "Length"; int blkLenWidth = Align.calculateWidth(blkLen, dataSize / blockCnt * 10); String rawSize = "Raw-Size"; int rawSizeWidth = Align.calculateWidth(rawSize, dataSizeUncompressed / blockCnt * 10); String records = "Records"; int recordsWidth = Align.calculateWidth(records, reader.getEntryCount() / blockCnt * 10); String endKey = "End-Key"; int endKeyWidth = Math.max(endKey.length(), maxKeySampleLen * 2 + 5); out.printf("%s %s %s %s %s %s\n", Align.format(blkID, blkIDWidth, Align.CENTER), Align.format(offset, offsetWidth, Align.CENTER), Align.format(blkLen, blkLenWidth, Align.CENTER), Align.format( rawSize, rawSizeWidth, Align.CENTER), Align.format(records, recordsWidth, Align.CENTER), Align.format(endKey, endKeyWidth, Align.LEFT)); for (int i = 0; i < blockCnt; ++i) { BlockRegion region = reader.readerBCF.dataIndex.getBlockRegionList().get(i); TFileIndexEntry indexEntry = reader.tfileIndex.getEntry(i); out.printf("%s %s %s %s %s ", Align.format(Align.format(i, blkIDWidth2, Align.ZERO_PADDED), blkIDWidth, Align.LEFT), Align .format(region.getOffset(), offsetWidth, Align.LEFT), Align .format(region.getCompressedSize(), blkLenWidth, Align.LEFT), Align.format(region.getRawSize(), rawSizeWidth, Align.LEFT), Align.format(indexEntry.kvEntries, recordsWidth, Align.LEFT)); byte[] key = indexEntry.key; boolean asAscii = true; int sampleLen = Math.min(maxKeySampleLen, key.length); for (int j = 0; j < sampleLen; ++j) { byte b = key[j]; if ((b < 32 && b != 9) || (b == 127)) { asAscii = false; } } if (!asAscii) { out.print("0X"); for (int j = 0; j < sampleLen; ++j) { byte b = key[i]; out.printf("%X", b); } } else { out.print(new String(key, 0, sampleLen)); } if (sampleLen < key.length) { out.print("..."); } out.println(); } } out.println(); if (metaBlkCnt > 0) { String name = "Meta-Block"; int maxNameLen = 0; Set<Map.Entry<String, MetaIndexEntry>> metaBlkEntrySet = reader.readerBCF.metaIndex.index.entrySet(); for (Iterator<Map.Entry<String, MetaIndexEntry>> it = metaBlkEntrySet.iterator(); it.hasNext();) { Map.Entry<String, MetaIndexEntry> e = it.next(); if (e.getKey().length() > maxNameLen) { maxNameLen = e.getKey().length(); } } int nameWidth = Math.max(name.length(), maxNameLen); String offset = "Offset"; int offsetWidth = Align.calculateWidth(offset, length); String blkLen = "Length"; int blkLenWidth = Align.calculateWidth(blkLen, metaSize / metaBlkCnt * 10); String rawSize = "Raw-Size"; int rawSizeWidth = Align.calculateWidth(rawSize, metaSizeUncompressed / metaBlkCnt * 10); String compression = "Compression"; int compressionWidth = compression.length(); out.printf("%s %s %s %s %s\n", Align.format(name, nameWidth, Align.CENTER), Align.format(offset, offsetWidth, Align.CENTER), Align.format(blkLen, blkLenWidth, Align.CENTER), Align.format( rawSize, rawSizeWidth, Align.CENTER), Align.format(compression, compressionWidth, Align.LEFT)); for (Iterator<Map.Entry<String, MetaIndexEntry>> it = metaBlkEntrySet.iterator(); it.hasNext();) { Map.Entry<String, MetaIndexEntry> e = it.next(); String blkName = e.getValue().getMetaName(); BlockRegion region = e.getValue().getRegion(); String blkCompression = e.getValue().getCompressionAlgorithm().getName(); out.printf("%s %s %s %s %s\n", Align.format(blkName, nameWidth, Align.LEFT), Align.format(region.getOffset(), offsetWidth, Align.LEFT), Align.format(region.getCompressedSize(), blkLenWidth, Align.LEFT), Align.format(region.getRawSize(), rawSizeWidth, Align.LEFT), Align.format(blkCompression, compressionWidth, Align.LEFT)); } } } finally { IOUtils.cleanup(LOG, reader, fsdis); } } }
public class class_name { static public void dumpInfo(String file, PrintStream out, Configuration conf) throws IOException { final int maxKeySampleLen = 16; Path path = new Path(file); FileSystem fs = path.getFileSystem(conf); long length = fs.getFileStatus(path).getLen(); FSDataInputStream fsdis = fs.open(path); TFile.Reader reader = new TFile.Reader(fsdis, length, conf); try { LinkedHashMap<String, String> properties = new LinkedHashMap<String, String>(); int blockCnt = reader.readerBCF.getBlockCount(); int metaBlkCnt = reader.readerBCF.metaIndex.index.size(); properties.put("BCFile Version", reader.readerBCF.version.toString()); properties.put("TFile Version", reader.tfileMeta.version.toString()); properties.put("File Length", Long.toString(length)); properties.put("Data Compression", reader.readerBCF .getDefaultCompressionName()); properties.put("Record Count", Long.toString(reader.getEntryCount())); properties.put("Sorted", Boolean.toString(reader.isSorted())); if (reader.isSorted()) { properties.put("Comparator", reader.getComparatorName()); // depends on control dependency: [if], data = [none] } properties.put("Data Block Count", Integer.toString(blockCnt)); long dataSize = 0, dataSizeUncompressed = 0; if (blockCnt > 0) { for (int i = 0; i < blockCnt; ++i) { BlockRegion region = reader.readerBCF.dataIndex.getBlockRegionList().get(i); dataSize += region.getCompressedSize(); // depends on control dependency: [for], data = [none] dataSizeUncompressed += region.getRawSize(); // depends on control dependency: [for], data = [none] } properties.put("Data Block Bytes", Long.toString(dataSize)); // depends on control dependency: [if], data = [none] if (reader.readerBCF.getDefaultCompressionName() != "none") { properties.put("Data Block Uncompressed Bytes", Long .toString(dataSizeUncompressed)); // depends on control dependency: [if], data = [none] properties.put("Data Block Compression Ratio", String.format( "1:%.1f", (double) dataSizeUncompressed / dataSize)); // depends on control dependency: [if], data = [none] } } properties.put("Meta Block Count", Integer.toString(metaBlkCnt)); long metaSize = 0, metaSizeUncompressed = 0; if (metaBlkCnt > 0) { Collection<MetaIndexEntry> metaBlks = reader.readerBCF.metaIndex.index.values(); boolean calculateCompression = false; for (Iterator<MetaIndexEntry> it = metaBlks.iterator(); it.hasNext();) { MetaIndexEntry e = it.next(); metaSize += e.getRegion().getCompressedSize(); // depends on control dependency: [for], data = [none] metaSizeUncompressed += e.getRegion().getRawSize(); // depends on control dependency: [for], data = [none] if (e.getCompressionAlgorithm() != Compression.Algorithm.NONE) { calculateCompression = true; // depends on control dependency: [if], data = [none] } } properties.put("Meta Block Bytes", Long.toString(metaSize)); // depends on control dependency: [if], data = [none] if (calculateCompression) { properties.put("Meta Block Uncompressed Bytes", Long .toString(metaSizeUncompressed)); // depends on control dependency: [if], data = [none] properties.put("Meta Block Compression Ratio", String.format( "1:%.1f", (double) metaSizeUncompressed / metaSize)); // depends on control dependency: [if], data = [none] } } properties.put("Meta-Data Size Ratio", String.format("1:%.1f", (double) dataSize / metaSize)); long leftOverBytes = length - dataSize - metaSize; long miscSize = BCFile.Magic.size() * 2 + Long.SIZE / Byte.SIZE + Version.size(); long metaIndexSize = leftOverBytes - miscSize; properties.put("Meta Block Index Bytes", Long.toString(metaIndexSize)); properties.put("Headers Etc Bytes", Long.toString(miscSize)); // Now output the properties table. int maxKeyLength = 0; Set<Map.Entry<String, String>> entrySet = properties.entrySet(); for (Iterator<Map.Entry<String, String>> it = entrySet.iterator(); it .hasNext();) { Map.Entry<String, String> e = it.next(); if (e.getKey().length() > maxKeyLength) { maxKeyLength = e.getKey().length(); // depends on control dependency: [if], data = [none] } } for (Iterator<Map.Entry<String, String>> it = entrySet.iterator(); it .hasNext();) { Map.Entry<String, String> e = it.next(); out.printf("%s : %s\n", Align.format(e.getKey(), maxKeyLength, Align.LEFT), e.getValue()); // depends on control dependency: [for], data = [none] } out.println(); reader.checkTFileDataIndex(); if (blockCnt > 0) { String blkID = "Data-Block"; int blkIDWidth = Align.calculateWidth(blkID, blockCnt); int blkIDWidth2 = Align.calculateWidth("", blockCnt); String offset = "Offset"; int offsetWidth = Align.calculateWidth(offset, length); String blkLen = "Length"; int blkLenWidth = Align.calculateWidth(blkLen, dataSize / blockCnt * 10); String rawSize = "Raw-Size"; int rawSizeWidth = Align.calculateWidth(rawSize, dataSizeUncompressed / blockCnt * 10); String records = "Records"; int recordsWidth = Align.calculateWidth(records, reader.getEntryCount() / blockCnt * 10); String endKey = "End-Key"; int endKeyWidth = Math.max(endKey.length(), maxKeySampleLen * 2 + 5); out.printf("%s %s %s %s %s %s\n", Align.format(blkID, blkIDWidth, Align.CENTER), Align.format(offset, offsetWidth, Align.CENTER), Align.format(blkLen, blkLenWidth, Align.CENTER), Align.format( rawSize, rawSizeWidth, Align.CENTER), Align.format(records, recordsWidth, Align.CENTER), Align.format(endKey, endKeyWidth, Align.LEFT)); // depends on control dependency: [if], data = [none] for (int i = 0; i < blockCnt; ++i) { BlockRegion region = reader.readerBCF.dataIndex.getBlockRegionList().get(i); TFileIndexEntry indexEntry = reader.tfileIndex.getEntry(i); out.printf("%s %s %s %s %s ", Align.format(Align.format(i, blkIDWidth2, Align.ZERO_PADDED), blkIDWidth, Align.LEFT), Align .format(region.getOffset(), offsetWidth, Align.LEFT), Align .format(region.getCompressedSize(), blkLenWidth, Align.LEFT), Align.format(region.getRawSize(), rawSizeWidth, Align.LEFT), Align.format(indexEntry.kvEntries, recordsWidth, Align.LEFT)); // depends on control dependency: [for], data = [i] byte[] key = indexEntry.key; boolean asAscii = true; int sampleLen = Math.min(maxKeySampleLen, key.length); for (int j = 0; j < sampleLen; ++j) { byte b = key[j]; if ((b < 32 && b != 9) || (b == 127)) { asAscii = false; // depends on control dependency: [if], data = [none] } } if (!asAscii) { out.print("0X"); // depends on control dependency: [if], data = [none] for (int j = 0; j < sampleLen; ++j) { byte b = key[i]; out.printf("%X", b); // depends on control dependency: [for], data = [none] } } else { out.print(new String(key, 0, sampleLen)); // depends on control dependency: [if], data = [none] } if (sampleLen < key.length) { out.print("..."); // depends on control dependency: [if], data = [none] } out.println(); // depends on control dependency: [for], data = [none] } } out.println(); if (metaBlkCnt > 0) { String name = "Meta-Block"; int maxNameLen = 0; Set<Map.Entry<String, MetaIndexEntry>> metaBlkEntrySet = reader.readerBCF.metaIndex.index.entrySet(); for (Iterator<Map.Entry<String, MetaIndexEntry>> it = metaBlkEntrySet.iterator(); it.hasNext();) { Map.Entry<String, MetaIndexEntry> e = it.next(); if (e.getKey().length() > maxNameLen) { maxNameLen = e.getKey().length(); // depends on control dependency: [if], data = [none] } } int nameWidth = Math.max(name.length(), maxNameLen); String offset = "Offset"; int offsetWidth = Align.calculateWidth(offset, length); String blkLen = "Length"; int blkLenWidth = Align.calculateWidth(blkLen, metaSize / metaBlkCnt * 10); String rawSize = "Raw-Size"; int rawSizeWidth = Align.calculateWidth(rawSize, metaSizeUncompressed / metaBlkCnt * 10); String compression = "Compression"; int compressionWidth = compression.length(); out.printf("%s %s %s %s %s\n", Align.format(name, nameWidth, Align.CENTER), Align.format(offset, offsetWidth, Align.CENTER), Align.format(blkLen, blkLenWidth, Align.CENTER), Align.format( rawSize, rawSizeWidth, Align.CENTER), Align.format(compression, compressionWidth, Align.LEFT)); // depends on control dependency: [if], data = [none] for (Iterator<Map.Entry<String, MetaIndexEntry>> it = metaBlkEntrySet.iterator(); it.hasNext();) { Map.Entry<String, MetaIndexEntry> e = it.next(); String blkName = e.getValue().getMetaName(); BlockRegion region = e.getValue().getRegion(); String blkCompression = e.getValue().getCompressionAlgorithm().getName(); out.printf("%s %s %s %s %s\n", Align.format(blkName, nameWidth, Align.LEFT), Align.format(region.getOffset(), offsetWidth, Align.LEFT), Align.format(region.getCompressedSize(), blkLenWidth, Align.LEFT), Align.format(region.getRawSize(), rawSizeWidth, Align.LEFT), Align.format(blkCompression, compressionWidth, Align.LEFT)); // depends on control dependency: [for], data = [none] } } } finally { IOUtils.cleanup(LOG, reader, fsdis); } } }
public class class_name { public void setOwner(HttpServiceContext hsc) { // if we have an SC owner, set it's flag to false if (null != getServiceContext()) { getServiceContext().setRequestOwner(false); } // if the owner is a new HSC, then init the flags if (null != hsc) { super.init(hsc); getServiceContext().setRequestOwner(true); setIncoming(getServiceContext().isInboundConnection()); } } }
public class class_name { public void setOwner(HttpServiceContext hsc) { // if we have an SC owner, set it's flag to false if (null != getServiceContext()) { getServiceContext().setRequestOwner(false); // depends on control dependency: [if], data = [none] } // if the owner is a new HSC, then init the flags if (null != hsc) { super.init(hsc); // depends on control dependency: [if], data = [hsc)] getServiceContext().setRequestOwner(true); // depends on control dependency: [if], data = [none] setIncoming(getServiceContext().isInboundConnection()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public BundleLinkComponent getLinkOrCreate(String theRelation) { org.apache.commons.lang3.Validate.notBlank(theRelation, "theRelation may not be null or empty"); for (BundleLinkComponent next : getLink()) { if (theRelation.equals(next.getRelation())) { return next; } } BundleLinkComponent retVal = new BundleLinkComponent(); retVal.setRelation(theRelation); getLink().add(retVal); return retVal; } }
public class class_name { public BundleLinkComponent getLinkOrCreate(String theRelation) { org.apache.commons.lang3.Validate.notBlank(theRelation, "theRelation may not be null or empty"); for (BundleLinkComponent next : getLink()) { if (theRelation.equals(next.getRelation())) { return next; // depends on control dependency: [if], data = [none] } } BundleLinkComponent retVal = new BundleLinkComponent(); retVal.setRelation(theRelation); getLink().add(retVal); return retVal; } }
public class class_name { private XmlElement replacePrimaryKeyXmlElement(IntrospectedTable introspectedTable, XmlElement element, String id, boolean update) { XmlElement withVersionEle = XmlElementTools.clone(element); XmlElementTools.replaceAttribute(withVersionEle, new Attribute("id", id)); XmlElementTools.replaceAttribute(withVersionEle, new Attribute("parameterType", "map")); FormatTools.replaceComment(commentGenerator, withVersionEle); // 替换查询语句 Iterator<Element> elementIterator = withVersionEle.getElements().iterator(); boolean flag = false; while (elementIterator.hasNext()) { Element ele = elementIterator.next(); if (ele instanceof TextElement && ((TextElement) ele).getContent().matches(".*where.*")) { flag = true; } if (flag) { elementIterator.remove(); } } // where 语句 withVersionEle.addElement(new TextElement("where " + this.generateVersionEleStr())); if (introspectedTable.getPrimaryKeyColumns().size() == 1) { IntrospectedColumn introspectedColumn = introspectedTable.getPrimaryKeyColumns().get(0); StringBuilder sb = new StringBuilder(); sb.append(" and "); sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn)); sb.append(" = "); if (update) { sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, "record.")); } else { sb.append("#{key,jdbcType="); sb.append(introspectedColumn.getJdbcTypeName()); if (StringUtility.stringHasValue(introspectedColumn.getTypeHandler())) { sb.append(",typeHandler="); sb.append(introspectedColumn.getTypeHandler()); } sb.append("}"); } withVersionEle.addElement(new TextElement(sb.toString())); } else { for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) { StringBuilder sb = new StringBuilder(); sb.append(" and "); sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn)); sb.append(" = "); sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, update ? "record." : "key.")); withVersionEle.addElement(new TextElement(sb.toString())); } } return withVersionEle; } }
public class class_name { private XmlElement replacePrimaryKeyXmlElement(IntrospectedTable introspectedTable, XmlElement element, String id, boolean update) { XmlElement withVersionEle = XmlElementTools.clone(element); XmlElementTools.replaceAttribute(withVersionEle, new Attribute("id", id)); XmlElementTools.replaceAttribute(withVersionEle, new Attribute("parameterType", "map")); FormatTools.replaceComment(commentGenerator, withVersionEle); // 替换查询语句 Iterator<Element> elementIterator = withVersionEle.getElements().iterator(); boolean flag = false; while (elementIterator.hasNext()) { Element ele = elementIterator.next(); if (ele instanceof TextElement && ((TextElement) ele).getContent().matches(".*where.*")) { flag = true; // depends on control dependency: [if], data = [none] } if (flag) { elementIterator.remove(); // depends on control dependency: [if], data = [none] } } // where 语句 withVersionEle.addElement(new TextElement("where " + this.generateVersionEleStr())); if (introspectedTable.getPrimaryKeyColumns().size() == 1) { IntrospectedColumn introspectedColumn = introspectedTable.getPrimaryKeyColumns().get(0); StringBuilder sb = new StringBuilder(); sb.append(" and "); sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn)); sb.append(" = "); if (update) { sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, "record.")); // depends on control dependency: [if], data = [none] } else { sb.append("#{key,jdbcType="); // depends on control dependency: [if], data = [none] sb.append(introspectedColumn.getJdbcTypeName()); // depends on control dependency: [if], data = [none] if (StringUtility.stringHasValue(introspectedColumn.getTypeHandler())) { sb.append(",typeHandler="); // depends on control dependency: [if], data = [none] sb.append(introspectedColumn.getTypeHandler()); // depends on control dependency: [if], data = [none] } sb.append("}"); // depends on control dependency: [if], data = [none] } withVersionEle.addElement(new TextElement(sb.toString())); } else { for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) { StringBuilder sb = new StringBuilder(); sb.append(" and "); sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn)); sb.append(" = "); sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, update ? "record." : "key.")); withVersionEle.addElement(new TextElement(sb.toString())); } } return withVersionEle; } }
public class class_name { public void marshall(TaskObject taskObject, ProtocolMarshaller protocolMarshaller) { if (taskObject == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(taskObject.getTaskId(), TASKID_BINDING); protocolMarshaller.marshall(taskObject.getPipelineId(), PIPELINEID_BINDING); protocolMarshaller.marshall(taskObject.getAttemptId(), ATTEMPTID_BINDING); protocolMarshaller.marshall(taskObject.getObjects(), OBJECTS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(TaskObject taskObject, ProtocolMarshaller protocolMarshaller) { if (taskObject == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(taskObject.getTaskId(), TASKID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(taskObject.getPipelineId(), PIPELINEID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(taskObject.getAttemptId(), ATTEMPTID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(taskObject.getObjects(), OBJECTS_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 static boolean isValidIfNumber(Object obj) { if (obj != null && obj instanceof Number) { if (obj instanceof Double) { if (((Double) obj).isInfinite() || ((Double) obj).isNaN()) { return false; } } else if (obj instanceof Float) { if (((Float) obj).isInfinite() || ((Float) obj).isNaN()) { return false; } } } return true; } }
public class class_name { public static boolean isValidIfNumber(Object obj) { if (obj != null && obj instanceof Number) { if (obj instanceof Double) { if (((Double) obj).isInfinite() || ((Double) obj).isNaN()) { return false; // depends on control dependency: [if], data = [none] } } else if (obj instanceof Float) { if (((Float) obj).isInfinite() || ((Float) obj).isNaN()) { return false; // depends on control dependency: [if], data = [none] } } } return true; } }
public class class_name { public void marshall(UpdateUserRequest updateUserRequest, ProtocolMarshaller protocolMarshaller) { if (updateUserRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateUserRequest.getAuthenticationToken(), AUTHENTICATIONTOKEN_BINDING); protocolMarshaller.marshall(updateUserRequest.getUserId(), USERID_BINDING); protocolMarshaller.marshall(updateUserRequest.getGivenName(), GIVENNAME_BINDING); protocolMarshaller.marshall(updateUserRequest.getSurname(), SURNAME_BINDING); protocolMarshaller.marshall(updateUserRequest.getType(), TYPE_BINDING); protocolMarshaller.marshall(updateUserRequest.getStorageRule(), STORAGERULE_BINDING); protocolMarshaller.marshall(updateUserRequest.getTimeZoneId(), TIMEZONEID_BINDING); protocolMarshaller.marshall(updateUserRequest.getLocale(), LOCALE_BINDING); protocolMarshaller.marshall(updateUserRequest.getGrantPoweruserPrivileges(), GRANTPOWERUSERPRIVILEGES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(UpdateUserRequest updateUserRequest, ProtocolMarshaller protocolMarshaller) { if (updateUserRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateUserRequest.getAuthenticationToken(), AUTHENTICATIONTOKEN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateUserRequest.getUserId(), USERID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateUserRequest.getGivenName(), GIVENNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateUserRequest.getSurname(), SURNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateUserRequest.getType(), TYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateUserRequest.getStorageRule(), STORAGERULE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateUserRequest.getTimeZoneId(), TIMEZONEID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateUserRequest.getLocale(), LOCALE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateUserRequest.getGrantPoweruserPrivileges(), GRANTPOWERUSERPRIVILEGES_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 { private static PublicKey getPublicKey(String modulus, String exponent) { try { BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); return keyFactory.generatePublic(keySpec); } catch (Exception e) { LogUtil.writeErrorLog("构造RSA公钥失败:" + e); return null; } } }
public class class_name { private static PublicKey getPublicKey(String modulus, String exponent) { try { BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); return keyFactory.generatePublic(keySpec); // depends on control dependency: [try], data = [none] } catch (Exception e) { LogUtil.writeErrorLog("构造RSA公钥失败:" + e); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { static void execute(Tenant tenant, Runnable runnable) { startTenantFlow(); try { getThreadLocalInstance().setTenant(tenant); runnable.run(); } finally { endTenantFlow(); } } }
public class class_name { static void execute(Tenant tenant, Runnable runnable) { startTenantFlow(); try { getThreadLocalInstance().setTenant(tenant); // depends on control dependency: [try], data = [none] runnable.run(); // depends on control dependency: [try], data = [none] } finally { endTenantFlow(); } } }
public class class_name { public Instruction createList(final Instruction _newTail) { Instruction childExprHead = null; if (_newTail == null) { childExprHead = head; tail = head = null; } else { childExprHead = _newTail.getNextExpr(); tail = _newTail; _newTail.setNextExpr(null); if (childExprHead != null) { childExprHead.setPrevExpr(null); } } return (childExprHead); } }
public class class_name { public Instruction createList(final Instruction _newTail) { Instruction childExprHead = null; if (_newTail == null) { childExprHead = head; // depends on control dependency: [if], data = [none] tail = head = null; // depends on control dependency: [if], data = [none] } else { childExprHead = _newTail.getNextExpr(); // depends on control dependency: [if], data = [none] tail = _newTail; // depends on control dependency: [if], data = [none] _newTail.setNextExpr(null); // depends on control dependency: [if], data = [null)] if (childExprHead != null) { childExprHead.setPrevExpr(null); // depends on control dependency: [if], data = [null)] } } return (childExprHead); } }
public class class_name { protected void unfoldModules(JSONObject modules, Map<Integer, String> sparseArray) throws IOException, JSONException { final String sourceMethod = "unfoldModules"; //$NON-NLS-1$ if (isTraceLogging) { log.entering(RequestedModuleNames.class.getName(), sourceMethod, new Object[]{modules, sparseArray}); } Iterator<?> it = modules.keys(); String[] prefixes = null; if (modules.containsKey(PLUGIN_PREFIXES_PROP_NAME)) { @SuppressWarnings("unchecked") Map<String, String> oPrefixes = (Map<String, String>) modules.get(PLUGIN_PREFIXES_PROP_NAME); prefixes = new String[oPrefixes.size()]; for (String key : oPrefixes.keySet()) { prefixes[Integer.parseInt(oPrefixes.get(key))] = key; } } while (it.hasNext()) { String key = (String) it.next(); if (!NON_PATH_PROP_PATTERN.matcher(key).find()) { unfoldModulesHelper(modules.get(key), key, prefixes, sparseArray); } } if (isTraceLogging) { log.exiting(RequestedModuleNames.class.getName(), sourceMethod, sparseArray); } } }
public class class_name { protected void unfoldModules(JSONObject modules, Map<Integer, String> sparseArray) throws IOException, JSONException { final String sourceMethod = "unfoldModules"; //$NON-NLS-1$ if (isTraceLogging) { log.entering(RequestedModuleNames.class.getName(), sourceMethod, new Object[]{modules, sparseArray}); } Iterator<?> it = modules.keys(); String[] prefixes = null; if (modules.containsKey(PLUGIN_PREFIXES_PROP_NAME)) { @SuppressWarnings("unchecked") Map<String, String> oPrefixes = (Map<String, String>) modules.get(PLUGIN_PREFIXES_PROP_NAME); prefixes = new String[oPrefixes.size()]; for (String key : oPrefixes.keySet()) { prefixes[Integer.parseInt(oPrefixes.get(key))] = key; // depends on control dependency: [for], data = [key] } } while (it.hasNext()) { String key = (String) it.next(); if (!NON_PATH_PROP_PATTERN.matcher(key).find()) { unfoldModulesHelper(modules.get(key), key, prefixes, sparseArray); } } if (isTraceLogging) { log.exiting(RequestedModuleNames.class.getName(), sourceMethod, sparseArray); } } }
public class class_name { public static void assertNull(Object object, String format, Object... args) { if (imp != null && object != null) { imp.assertFailed(String.format(format, args)); } } }
public class class_name { public static void assertNull(Object object, String format, Object... args) { if (imp != null && object != null) { imp.assertFailed(String.format(format, args)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void registerLookupBundles(final List<GuiceyBundle> bundles) { setScope(ConfigScope.BundleLookup.getType()); for (GuiceyBundle bundle : bundles) { register(ConfigItem.Bundle, bundle); } closeScope(); lifecycle().bundlesFromLookupResolved(bundles); lifecycle().bundlesResolved(getEnabledBundles(), getDisabledBundles()); } }
public class class_name { public void registerLookupBundles(final List<GuiceyBundle> bundles) { setScope(ConfigScope.BundleLookup.getType()); for (GuiceyBundle bundle : bundles) { register(ConfigItem.Bundle, bundle); // depends on control dependency: [for], data = [bundle] } closeScope(); lifecycle().bundlesFromLookupResolved(bundles); lifecycle().bundlesResolved(getEnabledBundles(), getDisabledBundles()); } }
public class class_name { @Override public Tuple createTuple(EntityKeyMetadata entityKeyMetadata, OperationContext operationContext) { Tuple tuple = null; CreateTuple createTuple = new CreateTupleImpl( entityKeyMetadata ); try { tuple = super.createTuple( entityKeyMetadata, operationContext ); } catch (Exception e) { handleException( createTuple, e ); } handleAppliedOperation( createTuple ); return tuple; } }
public class class_name { @Override public Tuple createTuple(EntityKeyMetadata entityKeyMetadata, OperationContext operationContext) { Tuple tuple = null; CreateTuple createTuple = new CreateTupleImpl( entityKeyMetadata ); try { tuple = super.createTuple( entityKeyMetadata, operationContext ); // depends on control dependency: [try], data = [none] } catch (Exception e) { handleException( createTuple, e ); } // depends on control dependency: [catch], data = [none] handleAppliedOperation( createTuple ); return tuple; } }
public class class_name { public static Sketch heapify(final Memory srcMem, final long seed) { final int serVer = srcMem.getByte(SER_VER_BYTE); if (serVer == 3) { final byte famID = srcMem.getByte(FAMILY_BYTE); final boolean ordered = (srcMem.getByte(FLAGS_BYTE) & ORDERED_FLAG_MASK) != 0; return constructHeapSketch(famID, ordered, srcMem, seed); } if (serVer == 1) { return ForwardCompatibility.heapify1to3(srcMem, seed); } if (serVer == 2) { return ForwardCompatibility.heapify2to3(srcMem, seed); } throw new SketchesArgumentException("Unknown Serialization Version: " + serVer); } }
public class class_name { public static Sketch heapify(final Memory srcMem, final long seed) { final int serVer = srcMem.getByte(SER_VER_BYTE); if (serVer == 3) { final byte famID = srcMem.getByte(FAMILY_BYTE); final boolean ordered = (srcMem.getByte(FLAGS_BYTE) & ORDERED_FLAG_MASK) != 0; return constructHeapSketch(famID, ordered, srcMem, seed); // depends on control dependency: [if], data = [none] } if (serVer == 1) { return ForwardCompatibility.heapify1to3(srcMem, seed); // depends on control dependency: [if], data = [none] } if (serVer == 2) { return ForwardCompatibility.heapify2to3(srcMem, seed); // depends on control dependency: [if], data = [none] } throw new SketchesArgumentException("Unknown Serialization Version: " + serVer); } }
public class class_name { private NodeMetadata enrich(NodeMetadata nodeMetadata, Template template) { final NodeMetadataBuilder nodeMetadataBuilder = NodeMetadataBuilder .fromNodeMetadata(nodeMetadata); if (nodeMetadata.getHardware() == null) { nodeMetadataBuilder.hardware(template.getHardware()); } if (nodeMetadata.getImageId() == null) { nodeMetadataBuilder.imageId(template.getImage().getId()); } if (nodeMetadata.getLocation() == null) { nodeMetadataBuilder.location(template.getLocation()); } return nodeMetadataBuilder.build(); } }
public class class_name { private NodeMetadata enrich(NodeMetadata nodeMetadata, Template template) { final NodeMetadataBuilder nodeMetadataBuilder = NodeMetadataBuilder .fromNodeMetadata(nodeMetadata); if (nodeMetadata.getHardware() == null) { nodeMetadataBuilder.hardware(template.getHardware()); // depends on control dependency: [if], data = [none] } if (nodeMetadata.getImageId() == null) { nodeMetadataBuilder.imageId(template.getImage().getId()); // depends on control dependency: [if], data = [none] } if (nodeMetadata.getLocation() == null) { nodeMetadataBuilder.location(template.getLocation()); // depends on control dependency: [if], data = [none] } return nodeMetadataBuilder.build(); } }
public class class_name { public java.util.List<OptionVersion> getOptionGroupOptionVersions() { if (optionGroupOptionVersions == null) { optionGroupOptionVersions = new com.amazonaws.internal.SdkInternalList<OptionVersion>(); } return optionGroupOptionVersions; } }
public class class_name { public java.util.List<OptionVersion> getOptionGroupOptionVersions() { if (optionGroupOptionVersions == null) { optionGroupOptionVersions = new com.amazonaws.internal.SdkInternalList<OptionVersion>(); // depends on control dependency: [if], data = [none] } return optionGroupOptionVersions; } }
public class class_name { public static Sql newInstance( @NamedParam(value = "url", type = String.class, required = true) @NamedParam(value = "properties", type = Properties.class) @NamedParam(value = "driverClassName", type = String.class) @NamedParam(value = "driver", type = String.class) @NamedParam(value = "user", type = String.class) @NamedParam(value = "password", type = String.class) @NamedParam(value = "cacheNamedQueries", type = Boolean.class) @NamedParam(value = "cacheStatements", type = Boolean.class) @NamedParam(value = "enableNamedQueries", type = Boolean.class) @NamedParam(value = "resultSetConcurrency", type = Integer.class) @NamedParam(value = "resultSetHoldability", type = Integer.class) @NamedParam(value = "resultSetType", type = Integer.class) // TODO below will be deleted once we fix type checker to understand // readonly Map otherwise seen as Map<String, Serializable> @NamedParam(value = "unused", type = Object.class) Map<String, Object> args) throws SQLException, ClassNotFoundException { if (!args.containsKey("url")) throw new IllegalArgumentException("Argument 'url' is required"); if (args.get("url") == null) throw new IllegalArgumentException("Argument 'url' must not be null"); if (args.containsKey("driverClassName") && args.containsKey("driver")) throw new IllegalArgumentException("Only one of 'driverClassName' and 'driver' should be provided"); // Make a copy so destructive operations will not affect the caller Map<String, Object> sqlArgs = new HashMap<String, Object>(args); sqlArgs.remove("unused"); // TODO remove Object driverClassName = sqlArgs.remove("driverClassName"); if (driverClassName == null) driverClassName = sqlArgs.remove("driver"); if (driverClassName != null) loadDriver(driverClassName.toString()); Properties props = (Properties) sqlArgs.remove("properties"); if (props != null && sqlArgs.containsKey("user")) throw new IllegalArgumentException("Only one of 'properties' and 'user' should be supplied"); if (props != null && sqlArgs.containsKey("password")) throw new IllegalArgumentException("Only one of 'properties' and 'password' should be supplied"); if (sqlArgs.containsKey("user") ^ sqlArgs.containsKey("password")) throw new IllegalArgumentException("Found one but not both of 'user' and 'password'"); Object url = sqlArgs.remove("url"); Connection connection; LOG.fine("url = " + url); if (props != null) { connection = DriverManager.getConnection(url.toString(), props); if (LOG.isLoggable(Level.FINE)) { if (!props.containsKey("password")) { LOG.fine("props = " + props); } else { // don't log the password Properties propsCopy = new Properties(); propsCopy.putAll(props); propsCopy.setProperty("password", "***"); LOG.fine("props = " + propsCopy); } } } else if (sqlArgs.containsKey("user")) { Object user = sqlArgs.remove("user"); LOG.fine("user = " + user); Object password = sqlArgs.remove("password"); LOG.fine("password = " + (password == null ? "null" : "***")); connection = DriverManager.getConnection(url.toString(), (user == null ? null : user.toString()), (password == null ? null : password.toString())); } else { LOG.fine("No user/password specified"); connection = DriverManager.getConnection(url.toString()); } Sql result = (Sql) InvokerHelper.invokeConstructorOf(Sql.class, sqlArgs); result.setConnection(connection); return result; } }
public class class_name { public static Sql newInstance( @NamedParam(value = "url", type = String.class, required = true) @NamedParam(value = "properties", type = Properties.class) @NamedParam(value = "driverClassName", type = String.class) @NamedParam(value = "driver", type = String.class) @NamedParam(value = "user", type = String.class) @NamedParam(value = "password", type = String.class) @NamedParam(value = "cacheNamedQueries", type = Boolean.class) @NamedParam(value = "cacheStatements", type = Boolean.class) @NamedParam(value = "enableNamedQueries", type = Boolean.class) @NamedParam(value = "resultSetConcurrency", type = Integer.class) @NamedParam(value = "resultSetHoldability", type = Integer.class) @NamedParam(value = "resultSetType", type = Integer.class) // TODO below will be deleted once we fix type checker to understand // readonly Map otherwise seen as Map<String, Serializable> @NamedParam(value = "unused", type = Object.class) Map<String, Object> args) throws SQLException, ClassNotFoundException { if (!args.containsKey("url")) throw new IllegalArgumentException("Argument 'url' is required"); if (args.get("url") == null) throw new IllegalArgumentException("Argument 'url' must not be null"); if (args.containsKey("driverClassName") && args.containsKey("driver")) throw new IllegalArgumentException("Only one of 'driverClassName' and 'driver' should be provided"); // Make a copy so destructive operations will not affect the caller Map<String, Object> sqlArgs = new HashMap<String, Object>(args); sqlArgs.remove("unused"); // TODO remove Object driverClassName = sqlArgs.remove("driverClassName"); if (driverClassName == null) driverClassName = sqlArgs.remove("driver"); if (driverClassName != null) loadDriver(driverClassName.toString()); Properties props = (Properties) sqlArgs.remove("properties"); if (props != null && sqlArgs.containsKey("user")) throw new IllegalArgumentException("Only one of 'properties' and 'user' should be supplied"); if (props != null && sqlArgs.containsKey("password")) throw new IllegalArgumentException("Only one of 'properties' and 'password' should be supplied"); if (sqlArgs.containsKey("user") ^ sqlArgs.containsKey("password")) throw new IllegalArgumentException("Found one but not both of 'user' and 'password'"); Object url = sqlArgs.remove("url"); Connection connection; LOG.fine("url = " + url); if (props != null) { connection = DriverManager.getConnection(url.toString(), props); if (LOG.isLoggable(Level.FINE)) { if (!props.containsKey("password")) { LOG.fine("props = " + props); // depends on control dependency: [if], data = [none] } else { // don't log the password Properties propsCopy = new Properties(); propsCopy.putAll(props); // depends on control dependency: [if], data = [none] propsCopy.setProperty("password", "***"); // depends on control dependency: [if], data = [none] LOG.fine("props = " + propsCopy); // depends on control dependency: [if], data = [none] } } } else if (sqlArgs.containsKey("user")) { Object user = sqlArgs.remove("user"); LOG.fine("user = " + user); Object password = sqlArgs.remove("password"); LOG.fine("password = " + (password == null ? "null" : "***")); connection = DriverManager.getConnection(url.toString(), (user == null ? null : user.toString()), (password == null ? null : password.toString())); } else { LOG.fine("No user/password specified"); connection = DriverManager.getConnection(url.toString()); } Sql result = (Sql) InvokerHelper.invokeConstructorOf(Sql.class, sqlArgs); result.setConnection(connection); return result; } }
public class class_name { protected void printFiller(PrintWriter pw) { if (this.options.getIndent() > 0) { for (int i = 0; i < options.getIndent(); i++) { pw.append(' '); } } } }
public class class_name { protected void printFiller(PrintWriter pw) { if (this.options.getIndent() > 0) { for (int i = 0; i < options.getIndent(); i++) { pw.append(' '); // depends on control dependency: [for], data = [none] } } } }
public class class_name { private void generateTin( List<Coordinate> coordinateList ) { pm.beginTask("Generate tin...", -1); DelaunayTriangulationBuilder b = new DelaunayTriangulationBuilder(); b.setSites(coordinateList); Geometry tinTriangles = b.getTriangles(gf); tinGeometries = new Geometry[tinTriangles.getNumGeometries()]; for( int i = 0; i < tinTriangles.getNumGeometries(); i++ ) { tinGeometries[i] = tinTriangles.getGeometryN(i); } pm.done(); } }
public class class_name { private void generateTin( List<Coordinate> coordinateList ) { pm.beginTask("Generate tin...", -1); DelaunayTriangulationBuilder b = new DelaunayTriangulationBuilder(); b.setSites(coordinateList); Geometry tinTriangles = b.getTriangles(gf); tinGeometries = new Geometry[tinTriangles.getNumGeometries()]; for( int i = 0; i < tinTriangles.getNumGeometries(); i++ ) { tinGeometries[i] = tinTriangles.getGeometryN(i); // depends on control dependency: [for], data = [i] } pm.done(); } }
public class class_name { public Object getRealObjectIfMaterialized(Object objectOrProxy) { if(isNormalOjbProxy(objectOrProxy)) { String msg; try { IndirectionHandler handler = getIndirectionHandler(objectOrProxy); return handler.alreadyMaterialized() ? handler.getRealSubject() : null; } catch(ClassCastException e) { // shouldn't happen but still ... msg = "The InvocationHandler for the provided Proxy was not an instance of " + IndirectionHandler.class.getName(); log.error(msg); throw new PersistenceBrokerException(msg, e); } catch(IllegalArgumentException e) { msg = "Could not retrieve real object for given Proxy: " + objectOrProxy; log.error(msg); throw new PersistenceBrokerException(msg, e); } catch(PersistenceBrokerException e) { log.error("Could not retrieve real object for given Proxy: " + objectOrProxy); throw e; } } else if(isVirtualOjbProxy(objectOrProxy)) { try { VirtualProxy proxy = (VirtualProxy) objectOrProxy; return proxy.alreadyMaterialized() ? proxy.getRealSubject() : null; } catch(PersistenceBrokerException e) { log.error("Could not retrieve real object for VirtualProxy: " + objectOrProxy); throw e; } } else { return objectOrProxy; } } }
public class class_name { public Object getRealObjectIfMaterialized(Object objectOrProxy) { if(isNormalOjbProxy(objectOrProxy)) { String msg; try { IndirectionHandler handler = getIndirectionHandler(objectOrProxy); return handler.alreadyMaterialized() ? handler.getRealSubject() : null; // depends on control dependency: [try], data = [none] } catch(ClassCastException e) { // shouldn't happen but still ... msg = "The InvocationHandler for the provided Proxy was not an instance of " + IndirectionHandler.class.getName(); log.error(msg); throw new PersistenceBrokerException(msg, e); } // depends on control dependency: [catch], data = [none] catch(IllegalArgumentException e) { msg = "Could not retrieve real object for given Proxy: " + objectOrProxy; log.error(msg); throw new PersistenceBrokerException(msg, e); } // depends on control dependency: [catch], data = [none] catch(PersistenceBrokerException e) { log.error("Could not retrieve real object for given Proxy: " + objectOrProxy); throw e; } // depends on control dependency: [catch], data = [none] } else if(isVirtualOjbProxy(objectOrProxy)) { try { VirtualProxy proxy = (VirtualProxy) objectOrProxy; return proxy.alreadyMaterialized() ? proxy.getRealSubject() : null; // depends on control dependency: [try], data = [none] } catch(PersistenceBrokerException e) { log.error("Could not retrieve real object for VirtualProxy: " + objectOrProxy); throw e; } // depends on control dependency: [catch], data = [none] } else { return objectOrProxy; // depends on control dependency: [if], data = [none] } } }
public class class_name { static public File computeNunaliitDir(File installDir) { while( null != installDir ){ // The root of the nunalii2 project contains "nunaliit2-couch-command", // "nunaliit2-couch-sdk" and "nunaliit2-js" boolean commandExists = (new File(installDir, "nunaliit2-couch-command")).exists(); boolean sdkExists = (new File(installDir, "nunaliit2-couch-sdk")).exists(); boolean jsExists = (new File(installDir, "nunaliit2-js")).exists(); if( commandExists && sdkExists && jsExists ){ return installDir; } else { // Go to parent installDir = installDir.getParentFile(); } } return null; } }
public class class_name { static public File computeNunaliitDir(File installDir) { while( null != installDir ){ // The root of the nunalii2 project contains "nunaliit2-couch-command", // "nunaliit2-couch-sdk" and "nunaliit2-js" boolean commandExists = (new File(installDir, "nunaliit2-couch-command")).exists(); boolean sdkExists = (new File(installDir, "nunaliit2-couch-sdk")).exists(); boolean jsExists = (new File(installDir, "nunaliit2-js")).exists(); if( commandExists && sdkExists && jsExists ){ return installDir; // depends on control dependency: [if], data = [none] } else { // Go to parent installDir = installDir.getParentFile(); // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public static Last[][] setScoreVector(int x, int xb, int yb, int ye, int gop, int gep, int[] subs, boolean storing, int[][][] scores, int[] xyMax, int score) { Last[][] pointers; ensureScoringMatrixColumn(x, storing, scores); if (x == xb) { pointers = new Last[ye + 1][scores[0][0].length]; } else { pointers = new Last[ye + 1][]; pointers[0] = new Last[scores[0][0].length]; for (int y = 1; y < scores[0].length; y++) { pointers[y] = setScorePoint(x, y, gop, gep, subs[y], scores); for (int z = 0; z < scores[0][0].length; z++) { if (scores[x][y][z] <= 0) { scores[x][y][z] = 0; pointers[y][z] = null; } } if (scores[x][y][0] > score) { xyMax[0] = x; xyMax[1] = y; score = scores[x][y][0]; } } } return pointers; } }
public class class_name { public static Last[][] setScoreVector(int x, int xb, int yb, int ye, int gop, int gep, int[] subs, boolean storing, int[][][] scores, int[] xyMax, int score) { Last[][] pointers; ensureScoringMatrixColumn(x, storing, scores); if (x == xb) { pointers = new Last[ye + 1][scores[0][0].length]; // depends on control dependency: [if], data = [none] } else { pointers = new Last[ye + 1][]; // depends on control dependency: [if], data = [none] pointers[0] = new Last[scores[0][0].length]; // depends on control dependency: [if], data = [none] for (int y = 1; y < scores[0].length; y++) { pointers[y] = setScorePoint(x, y, gop, gep, subs[y], scores); // depends on control dependency: [for], data = [y] for (int z = 0; z < scores[0][0].length; z++) { if (scores[x][y][z] <= 0) { scores[x][y][z] = 0; // depends on control dependency: [if], data = [none] pointers[y][z] = null; // depends on control dependency: [if], data = [none] } } if (scores[x][y][0] > score) { xyMax[0] = x; // depends on control dependency: [if], data = [none] xyMax[1] = y; // depends on control dependency: [if], data = [none] score = scores[x][y][0]; // depends on control dependency: [if], data = [none] } } } return pointers; } }
public class class_name { public RiakFlag getFlag(BinaryValue key) { if (entries.containsKey(key)) { for (RiakDatatype dt : entries.get(key)) { if (dt.isFlag()) { return dt.getAsFlag(); } } } return null; } }
public class class_name { public RiakFlag getFlag(BinaryValue key) { if (entries.containsKey(key)) { for (RiakDatatype dt : entries.get(key)) { if (dt.isFlag()) { return dt.getAsFlag(); // depends on control dependency: [if], data = [none] } } } return null; } }
public class class_name { public void setIgnoreDependencyPattern(String ignoreDependencyPattern) { try { Pattern pattern = Pattern.compile(ignoreDependencyPattern); this.ignoreDependencyPattern = pattern; } catch (PatternSyntaxException e) { throw new BuildException("invalid ignore dependency pattern: " + e.getMessage()); } } }
public class class_name { public void setIgnoreDependencyPattern(String ignoreDependencyPattern) { try { Pattern pattern = Pattern.compile(ignoreDependencyPattern); this.ignoreDependencyPattern = pattern; // depends on control dependency: [try], data = [none] } catch (PatternSyntaxException e) { throw new BuildException("invalid ignore dependency pattern: " + e.getMessage()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private Collection<Class<? extends Saga>> removeAbstractTypes(final Collection<Class<? extends Saga>> foundTypes) { Collection<Class<? extends Saga>> sagaTypes = new ArrayList<>(); for (Class<? extends Saga> entryType : foundTypes) { if (!Modifier.isAbstract(entryType.getModifiers())) { sagaTypes.add(entryType); } } return sagaTypes; } }
public class class_name { private Collection<Class<? extends Saga>> removeAbstractTypes(final Collection<Class<? extends Saga>> foundTypes) { Collection<Class<? extends Saga>> sagaTypes = new ArrayList<>(); for (Class<? extends Saga> entryType : foundTypes) { if (!Modifier.isAbstract(entryType.getModifiers())) { sagaTypes.add(entryType); // depends on control dependency: [if], data = [none] } } return sagaTypes; } }
public class class_name { public byte[] sign(byte[] message) { try { // this way signatureInstance should be thread safe final Signature signatureInstance = ((provider == null) || (provider.length() == 0)) ? Signature .getInstance(algorithm) : Signature.getInstance(algorithm, provider); signatureInstance.initSign(privateKey); signatureInstance.update(message); return signatureInstance.sign(); } catch (Exception e) { throw new SignatureException("error generating the signature: algorithm=" + algorithm, e); } } }
public class class_name { public byte[] sign(byte[] message) { try { // this way signatureInstance should be thread safe final Signature signatureInstance = ((provider == null) || (provider.length() == 0)) ? Signature .getInstance(algorithm) : Signature.getInstance(algorithm, provider); signatureInstance.initSign(privateKey); // depends on control dependency: [try], data = [none] signatureInstance.update(message); // depends on control dependency: [try], data = [none] return signatureInstance.sign(); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SignatureException("error generating the signature: algorithm=" + algorithm, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String ifNotEmptyAppend(String chekString, String value) { if (hasText(chekString)) { return value+chekString; } else { return ""; } } }
public class class_name { public static String ifNotEmptyAppend(String chekString, String value) { if (hasText(chekString)) { return value+chekString; // depends on control dependency: [if], data = [none] } else { return ""; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String concat(String baseName, String... appendName) { if (appendName.length == 0) { return baseName; } StringBuilder concatName = new StringBuilder(); if (MoreStringUtil.endWith(baseName, Platforms.FILE_PATH_SEPARATOR_CHAR)) { concatName.append(baseName).append(appendName[0]); } else { concatName.append(baseName).append(Platforms.FILE_PATH_SEPARATOR_CHAR).append(appendName[0]); } if (appendName.length > 1) { for (int i = 1; i < appendName.length; i++) { concatName.append(Platforms.FILE_PATH_SEPARATOR_CHAR).append(appendName[i]); } } return concatName.toString(); } }
public class class_name { public static String concat(String baseName, String... appendName) { if (appendName.length == 0) { return baseName; // depends on control dependency: [if], data = [none] } StringBuilder concatName = new StringBuilder(); if (MoreStringUtil.endWith(baseName, Platforms.FILE_PATH_SEPARATOR_CHAR)) { concatName.append(baseName).append(appendName[0]); // depends on control dependency: [if], data = [none] } else { concatName.append(baseName).append(Platforms.FILE_PATH_SEPARATOR_CHAR).append(appendName[0]); // depends on control dependency: [if], data = [none] } if (appendName.length > 1) { for (int i = 1; i < appendName.length; i++) { concatName.append(Platforms.FILE_PATH_SEPARATOR_CHAR).append(appendName[i]); // depends on control dependency: [for], data = [i] } } return concatName.toString(); } }
public class class_name { protected void hookCurtainBefore(FwAssistantDirector assistantDirector) { final FwCoreDirection coreDirection = assistantDirector.assistCoreDirection(); final CurtainBeforeHook hook = coreDirection.assistCurtainBeforeHook(); if (hook != null) { hook.hook(assistantDirector); } BowgunCurtainBefore.handleBowgunCurtainBefore(assistantDirector); } }
public class class_name { protected void hookCurtainBefore(FwAssistantDirector assistantDirector) { final FwCoreDirection coreDirection = assistantDirector.assistCoreDirection(); final CurtainBeforeHook hook = coreDirection.assistCurtainBeforeHook(); if (hook != null) { hook.hook(assistantDirector); // depends on control dependency: [if], data = [none] } BowgunCurtainBefore.handleBowgunCurtainBefore(assistantDirector); } }
public class class_name { public static String byteArray2String(final byte[] array, final String prefix, final String delimiter, final boolean brackets, final int radix) { if (array == null) { return null; } final int maxlen = Integer.toString(0xFF, radix).length(); final String zero = "00000000"; final String normDelim = delimiter == null ? " " : delimiter; final String normPrefix = prefix == null ? "" : prefix; final StringBuilder result = new StringBuilder(array.length * 4); if (brackets) { result.append('['); } boolean nofirst = false; for (final byte b : array) { if (nofirst) { result.append(normDelim); } else { nofirst = true; } result.append(normPrefix); final String v = Integer.toString(b & 0xFF, radix); if (v.length() < maxlen) { result.append(zero, 0, maxlen - v.length()); } result.append(v.toUpperCase(Locale.ENGLISH)); } if (brackets) { result.append(']'); } return result.toString(); } }
public class class_name { public static String byteArray2String(final byte[] array, final String prefix, final String delimiter, final boolean brackets, final int radix) { if (array == null) { return null; // depends on control dependency: [if], data = [none] } final int maxlen = Integer.toString(0xFF, radix).length(); final String zero = "00000000"; final String normDelim = delimiter == null ? " " : delimiter; final String normPrefix = prefix == null ? "" : prefix; final StringBuilder result = new StringBuilder(array.length * 4); if (brackets) { result.append('['); // depends on control dependency: [if], data = [none] } boolean nofirst = false; for (final byte b : array) { if (nofirst) { result.append(normDelim); // depends on control dependency: [if], data = [none] } else { nofirst = true; // depends on control dependency: [if], data = [none] } result.append(normPrefix); // depends on control dependency: [for], data = [none] final String v = Integer.toString(b & 0xFF, radix); if (v.length() < maxlen) { result.append(zero, 0, maxlen - v.length()); // depends on control dependency: [if], data = [none] } result.append(v.toUpperCase(Locale.ENGLISH)); // depends on control dependency: [for], data = [none] } if (brackets) { result.append(']'); // depends on control dependency: [if], data = [none] } return result.toString(); } }
public class class_name { static <I, O> CipherExecutor<I, O> getInstance() { if (INSTANCE == null) { synchronized (NoOpCipherExecutor.class) { if (INSTANCE == null) { INSTANCE = new NoOpCipherExecutor<>(); } } } return INSTANCE; } }
public class class_name { static <I, O> CipherExecutor<I, O> getInstance() { if (INSTANCE == null) { synchronized (NoOpCipherExecutor.class) { // depends on control dependency: [if], data = [none] if (INSTANCE == null) { INSTANCE = new NoOpCipherExecutor<>(); // depends on control dependency: [if], data = [none] } } } return INSTANCE; } }
public class class_name { public void exec(@NonNull CustomOp op) { long st = profilingHookIn(op); if (op.numOutputArguments() == 0 && !op.isInplaceCall()) throw new ND4JIllegalStateException("Op name " + op.opName() + " failed to execute. You can't execute non-inplace CustomOp without outputs being specified"); val name = op.opName().toLowerCase(); val hash = op.opHash(); val inputShapes = getInputShapes(op.numInputArguments()); val inputBuffers = getInputBuffers(op.numInputArguments()); int cnt= 0; val inputArgs = op.inputArguments(); for (val in: inputArgs) { if(in == null){ throw new NullPointerException("Input argument is null"); } inputBuffers.put(cnt, in.data().addressPointer()); inputShapes.put(cnt++, in.shapeInfoDataBuffer().addressPointer()); } val outputArgs = op.outputArguments(); for(int i = 0; i < outputArgs.length; i++) { if(outputArgs[i] == null) throw new ND4JIllegalStateException("Op output arguments must not be null!"); } val outputShapes = getOutputShapes(op.numOutputArguments()); val outputBuffers = getOutputBuffers(op.numOutputArguments()); cnt= 0; for (val out: outputArgs) { outputBuffers.put(cnt, out.data().addressPointer()); outputShapes.put(cnt++, out.shapeInfoDataBuffer().addressPointer()); } val iArgs = op.numIArguments() > 0 ? new LongPointer(op.numIArguments()) : null; cnt = 0; val iArgs1 = op.iArgs(); for (val i: iArgs1) iArgs.put(cnt++, i); if (Nd4j.dataType() == DataBuffer.Type.FLOAT) { val tArgs = op.numTArguments() > 0 ? new FloatPointer(op.numTArguments()) : null; val tArgs1 = op.tArgs(); cnt = 0; for (val t: tArgs1) tArgs.put(cnt++, (float) t); OpStatus status = OpStatus.byNumber(loop.execCustomOpFloat(null, hash, inputBuffers, inputShapes, op.numInputArguments(), outputBuffers, outputShapes, op.numOutputArguments(), tArgs, op.numTArguments(), iArgs, op.numIArguments(), op.isInplaceCall())); if (status != OpStatus.ND4J_STATUS_OK) throw new ND4JIllegalStateException("Op execution failed: " + status); } else if (Nd4j.dataType() == DataBuffer.Type.DOUBLE) { val tArgs = op.numTArguments() > 0 ? getDoublePointerFrom(tArgsPointer,op.numTArguments()) : null; val tArgs1 = op.tArgs(); cnt = 0; for (val t: tArgs1) tArgs.put(cnt++, t); val t = op.numInputArguments(); OpStatus status = OpStatus.ND4J_STATUS_OK; try { status = OpStatus.byNumber(loop.execCustomOpDouble( null, hash, inputBuffers, inputShapes, op.numInputArguments(), outputBuffers, outputShapes, op.numOutputArguments(), tArgs, op.numTArguments(), iArgs, op.numIArguments(), op.isInplaceCall())); }catch(Exception e) { log.error("Failed to execute. Please see above message (printed out from c++) for a possible cause of error."); throw e; } } else if (Nd4j.dataType() == DataBuffer.Type.HALF) { val tArgs = op.numTArguments() > 0 ? getShortPointerFrom(halfArgsPointer,op.numTArguments()) : null; cnt = 0; val tArgs1 = op.tArgs(); for (val t: tArgs1) tArgs.put(cnt++, ArrayUtil.toHalf(t)); OpStatus status = OpStatus.byNumber(loop.execCustomOpHalf(null, hash, inputBuffers, inputShapes, op.numInputArguments(), outputBuffers, outputShapes, op.numOutputArguments(), tArgs, op.numTArguments(), iArgs, op.numIArguments(), op.isInplaceCall())); if (status != OpStatus.ND4J_STATUS_OK) throw new ND4JIllegalStateException("Op execution failed: " + status); } profilingHookOut(op, st); } }
public class class_name { public void exec(@NonNull CustomOp op) { long st = profilingHookIn(op); if (op.numOutputArguments() == 0 && !op.isInplaceCall()) throw new ND4JIllegalStateException("Op name " + op.opName() + " failed to execute. You can't execute non-inplace CustomOp without outputs being specified"); val name = op.opName().toLowerCase(); val hash = op.opHash(); val inputShapes = getInputShapes(op.numInputArguments()); val inputBuffers = getInputBuffers(op.numInputArguments()); int cnt= 0; val inputArgs = op.inputArguments(); for (val in: inputArgs) { if(in == null){ throw new NullPointerException("Input argument is null"); } inputBuffers.put(cnt, in.data().addressPointer()); // depends on control dependency: [for], data = [in] inputShapes.put(cnt++, in.shapeInfoDataBuffer().addressPointer()); // depends on control dependency: [for], data = [in] } val outputArgs = op.outputArguments(); for(int i = 0; i < outputArgs.length; i++) { if(outputArgs[i] == null) throw new ND4JIllegalStateException("Op output arguments must not be null!"); } val outputShapes = getOutputShapes(op.numOutputArguments()); val outputBuffers = getOutputBuffers(op.numOutputArguments()); cnt= 0; for (val out: outputArgs) { outputBuffers.put(cnt, out.data().addressPointer()); // depends on control dependency: [for], data = [out] outputShapes.put(cnt++, out.shapeInfoDataBuffer().addressPointer()); // depends on control dependency: [for], data = [out] } val iArgs = op.numIArguments() > 0 ? new LongPointer(op.numIArguments()) : null; cnt = 0; val iArgs1 = op.iArgs(); for (val i: iArgs1) iArgs.put(cnt++, i); if (Nd4j.dataType() == DataBuffer.Type.FLOAT) { val tArgs = op.numTArguments() > 0 ? new FloatPointer(op.numTArguments()) : null; val tArgs1 = op.tArgs(); cnt = 0; // depends on control dependency: [if], data = [none] for (val t: tArgs1) tArgs.put(cnt++, (float) t); OpStatus status = OpStatus.byNumber(loop.execCustomOpFloat(null, hash, inputBuffers, inputShapes, op.numInputArguments(), outputBuffers, outputShapes, op.numOutputArguments(), tArgs, op.numTArguments(), iArgs, op.numIArguments(), op.isInplaceCall())); if (status != OpStatus.ND4J_STATUS_OK) throw new ND4JIllegalStateException("Op execution failed: " + status); } else if (Nd4j.dataType() == DataBuffer.Type.DOUBLE) { val tArgs = op.numTArguments() > 0 ? getDoublePointerFrom(tArgsPointer,op.numTArguments()) : null; val tArgs1 = op.tArgs(); cnt = 0; // depends on control dependency: [if], data = [none] for (val t: tArgs1) tArgs.put(cnt++, t); val t = op.numInputArguments(); OpStatus status = OpStatus.ND4J_STATUS_OK; try { status = OpStatus.byNumber(loop.execCustomOpDouble( null, hash, inputBuffers, inputShapes, op.numInputArguments(), outputBuffers, outputShapes, op.numOutputArguments(), tArgs, op.numTArguments(), iArgs, op.numIArguments(), op.isInplaceCall())); // depends on control dependency: [try], data = [none] }catch(Exception e) { log.error("Failed to execute. Please see above message (printed out from c++) for a possible cause of error."); throw e; } // depends on control dependency: [catch], data = [none] } else if (Nd4j.dataType() == DataBuffer.Type.HALF) { val tArgs = op.numTArguments() > 0 ? getShortPointerFrom(halfArgsPointer,op.numTArguments()) : null; cnt = 0; // depends on control dependency: [if], data = [none] val tArgs1 = op.tArgs(); for (val t: tArgs1) tArgs.put(cnt++, ArrayUtil.toHalf(t)); OpStatus status = OpStatus.byNumber(loop.execCustomOpHalf(null, hash, inputBuffers, inputShapes, op.numInputArguments(), outputBuffers, outputShapes, op.numOutputArguments(), tArgs, op.numTArguments(), iArgs, op.numIArguments(), op.isInplaceCall())); if (status != OpStatus.ND4J_STATUS_OK) throw new ND4JIllegalStateException("Op execution failed: " + status); } profilingHookOut(op, st); } }
public class class_name { public static BigInteger fromUnsignedByteArray(byte[] buf, int off, int length) { byte[] mag = buf; if (off != 0 || length != buf.length) { mag = new byte[length]; System.arraycopy(buf, off, mag, 0, length); } return new BigInteger(1, mag); } }
public class class_name { public static BigInteger fromUnsignedByteArray(byte[] buf, int off, int length) { byte[] mag = buf; if (off != 0 || length != buf.length) { mag = new byte[length]; // depends on control dependency: [if], data = [none] System.arraycopy(buf, off, mag, 0, length); // depends on control dependency: [if], data = [none] } return new BigInteger(1, mag); } }
public class class_name { public void setListener(Listener listener) { if (null != listener) { listenerReference = new WeakReference<Listener>(listener); } else { listenerReference = null; } } }
public class class_name { public void setListener(Listener listener) { if (null != listener) { listenerReference = new WeakReference<Listener>(listener); // depends on control dependency: [if], data = [listener)] } else { listenerReference = null; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String getAbsolutePath(String classPath) { URL configUrl = Thread.currentThread().getContextClassLoader().getResource(classPath.substring(1)); if (configUrl == null) { configUrl = ResourceUtil.class.getResource(classPath); } if (configUrl == null) { return null; } try { return configUrl.toURI().getPath(); } catch (URISyntaxException e) { throw new RuntimeException(e); } } }
public class class_name { public static String getAbsolutePath(String classPath) { URL configUrl = Thread.currentThread().getContextClassLoader().getResource(classPath.substring(1)); if (configUrl == null) { configUrl = ResourceUtil.class.getResource(classPath); // depends on control dependency: [if], data = [none] } if (configUrl == null) { return null; // depends on control dependency: [if], data = [none] } try { return configUrl.toURI().getPath(); // depends on control dependency: [try], data = [none] } catch (URISyntaxException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static MutableDoubleTuple reverse( DoubleTuple t, MutableDoubleTuple result) { result = validate(t, result); if (t == result) { int n = t.getSize(); int nh = n / 2; for (int i = 0; i < nh; i++) { double temp = result.get(i); result.set(i, result.get(n - 1 - i)); result.set(n - 1 - i, temp); } } else { int n = t.getSize(); for (int i = 0; i < n; i++) { result.set(i, t.get(n - 1 - i)); } } return result; } }
public class class_name { public static MutableDoubleTuple reverse( DoubleTuple t, MutableDoubleTuple result) { result = validate(t, result); if (t == result) { int n = t.getSize(); int nh = n / 2; for (int i = 0; i < nh; i++) { double temp = result.get(i); result.set(i, result.get(n - 1 - i)); // depends on control dependency: [for], data = [i] result.set(n - 1 - i, temp); // depends on control dependency: [for], data = [i] } } else { int n = t.getSize(); for (int i = 0; i < n; i++) { result.set(i, t.get(n - 1 - i)); // depends on control dependency: [for], data = [i] } } return result; } }
public class class_name { public static <E> ErrorMessageFactory shouldBeLenientEqualByIgnoring(Object actual, List<String> rejectedFields, List<Object> expectedValues, List<String> ignoredFields) { if (rejectedFields.size() == 1) { if (ignoredFields.isEmpty()) { return new ShouldBeLenientEqualByIgnoring(actual, rejectedFields.get(0), expectedValues.get(0)); } else { return new ShouldBeLenientEqualByIgnoring(actual, rejectedFields.get(0), expectedValues.get(0), ignoredFields); } } else { if (ignoredFields.isEmpty()) { return new ShouldBeLenientEqualByIgnoring(actual, rejectedFields, expectedValues); } else { return new ShouldBeLenientEqualByIgnoring(actual, rejectedFields, expectedValues, ignoredFields); } } } }
public class class_name { public static <E> ErrorMessageFactory shouldBeLenientEqualByIgnoring(Object actual, List<String> rejectedFields, List<Object> expectedValues, List<String> ignoredFields) { if (rejectedFields.size() == 1) { if (ignoredFields.isEmpty()) { return new ShouldBeLenientEqualByIgnoring(actual, rejectedFields.get(0), expectedValues.get(0)); // depends on control dependency: [if], data = [none] } else { return new ShouldBeLenientEqualByIgnoring(actual, rejectedFields.get(0), expectedValues.get(0), ignoredFields); // depends on control dependency: [if], data = [none] } } else { if (ignoredFields.isEmpty()) { return new ShouldBeLenientEqualByIgnoring(actual, rejectedFields, expectedValues); // depends on control dependency: [if], data = [none] } else { return new ShouldBeLenientEqualByIgnoring(actual, rejectedFields, expectedValues, ignoredFields); // depends on control dependency: [if], data = [none] } } } }
public class class_name { protected void loadFromUrl(Properties props, URL url) { InputStream is = null; try { is = url.openStream(); props.load(is); } catch (IOException ex) { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, ex.getMessage(), ex); } } finally { try { if (is != null) is.close(); } catch (IOException ignore) {} } } }
public class class_name { protected void loadFromUrl(Properties props, URL url) { InputStream is = null; try { is = url.openStream(); // depends on control dependency: [try], data = [none] props.load(is); // depends on control dependency: [try], data = [none] } catch (IOException ex) { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, ex.getMessage(), ex); // depends on control dependency: [if], data = [none] } } finally { // depends on control dependency: [catch], data = [none] try { if (is != null) is.close(); } catch (IOException ignore) {} // depends on control dependency: [catch], data = [none] } } }
public class class_name { public static long optionalLongAttribute( final XMLStreamReader reader, final String namespace, final String localName, final long defaultValue) { final String value = reader.getAttributeValue(namespace, localName); if (value != null) { return Long.parseLong(value); } return defaultValue; } }
public class class_name { public static long optionalLongAttribute( final XMLStreamReader reader, final String namespace, final String localName, final long defaultValue) { final String value = reader.getAttributeValue(namespace, localName); if (value != null) { return Long.parseLong(value); // depends on control dependency: [if], data = [(value] } return defaultValue; } }
public class class_name { @Override public void setVariables(Map<String, String> variables) { injectVariables(variables, element); if (timeoutVariable != null) { timeout = timeoutVariable.getConvertedValue(variables); } } }
public class class_name { @Override public void setVariables(Map<String, String> variables) { injectVariables(variables, element); if (timeoutVariable != null) { timeout = timeoutVariable.getConvertedValue(variables); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static List<PredicatedHandler> getPredicatedHandlers(PredicatedHandlersProvider[] predicatedHandlersProviders) { List<PredicatedHandler> predicatedHandlers = new ArrayList<>(); if (predicatedHandlersProviders != null && predicatedHandlersProviders.length > 0) { for (PredicatedHandlersProvider predicatedHandlersProvider : predicatedHandlersProviders) { predicatedHandlers.addAll(predicatedHandlersProvider.getPredicatedHandlers()); } } return predicatedHandlers; } }
public class class_name { public static List<PredicatedHandler> getPredicatedHandlers(PredicatedHandlersProvider[] predicatedHandlersProviders) { List<PredicatedHandler> predicatedHandlers = new ArrayList<>(); if (predicatedHandlersProviders != null && predicatedHandlersProviders.length > 0) { for (PredicatedHandlersProvider predicatedHandlersProvider : predicatedHandlersProviders) { predicatedHandlers.addAll(predicatedHandlersProvider.getPredicatedHandlers()); // depends on control dependency: [for], data = [predicatedHandlersProvider] } } return predicatedHandlers; } }
public class class_name { @Override protected final String replaceImageUrl(final String cssUri, final String imageUrl) { if (!imageUrls.contains(imageUrl)) { imageUrls.add(imageUrl); return super.replaceImageUrl(cssUri, imageUrl); } LOG.debug("duplicate Image url detected: '{}', skipping dataUri replacement", imageUrl); return imageUrl; } }
public class class_name { @Override protected final String replaceImageUrl(final String cssUri, final String imageUrl) { if (!imageUrls.contains(imageUrl)) { imageUrls.add(imageUrl); // depends on control dependency: [if], data = [none] return super.replaceImageUrl(cssUri, imageUrl); // depends on control dependency: [if], data = [none] } LOG.debug("duplicate Image url detected: '{}', skipping dataUri replacement", imageUrl); return imageUrl; } }
public class class_name { public List<String> listEscapeJavaScript(final List<?> target) { if (target == null) { return null; } final List<String> result = new ArrayList<String>(target.size() + 2); for (final Object element : target) { result.add(escapeJavaScript(element)); } return result; } }
public class class_name { public List<String> listEscapeJavaScript(final List<?> target) { if (target == null) { return null; // depends on control dependency: [if], data = [none] } final List<String> result = new ArrayList<String>(target.size() + 2); for (final Object element : target) { result.add(escapeJavaScript(element)); // depends on control dependency: [for], data = [element] } return result; } }
public class class_name { public static void appendResponse(StringBuilder buffer, String response) { if (response != null && !response.isEmpty()) { if (buffer.length() > 0) { buffer.append("\r\n"); } buffer.append(response); } } }
public class class_name { public static void appendResponse(StringBuilder buffer, String response) { if (response != null && !response.isEmpty()) { if (buffer.length() > 0) { buffer.append("\r\n"); // depends on control dependency: [if], data = [none] } buffer.append(response); // depends on control dependency: [if], data = [(response] } } }
public class class_name { private static <T> CustomizationReferenceSupplier<T> wrapCustomizationInstance(T obj) { if (obj == null) { return null; } return new CustomizationReferenceSupplier<T>(obj); } }
public class class_name { private static <T> CustomizationReferenceSupplier<T> wrapCustomizationInstance(T obj) { if (obj == null) { return null; } // depends on control dependency: [if], data = [none] return new CustomizationReferenceSupplier<T>(obj); } }
public class class_name { @Override public void doMessageReceivedListeners(final long sessionId, final long sessionReadBytes, final Object message) { runManagementTask(new Runnable() { @Override public void run() { try { // The particular management listeners change on strategy, so get them here. for (final GatewayManagementListener listener : getManagementListeners()) { listener.doMessageReceived(GatewayManagementBeanImpl.this, sessionId); } markChanged(); // mark ourselves as changed, possibly tell listeners } catch (Exception ex) { logger.warn("Error during messageReceived gateway listener notifications:", ex); } } }); } }
public class class_name { @Override public void doMessageReceivedListeners(final long sessionId, final long sessionReadBytes, final Object message) { runManagementTask(new Runnable() { @Override public void run() { try { // The particular management listeners change on strategy, so get them here. for (final GatewayManagementListener listener : getManagementListeners()) { listener.doMessageReceived(GatewayManagementBeanImpl.this, sessionId); // depends on control dependency: [for], data = [listener] } markChanged(); // mark ourselves as changed, possibly tell listeners // depends on control dependency: [try], data = [none] } catch (Exception ex) { logger.warn("Error during messageReceived gateway listener notifications:", ex); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { public String toSql(boolean showParameters) { String sql; if(forPaginator){ sql = metaModel.getDialect().formSelect(null, null, fullQuery, orderBys, limit, offset); }else{ sql = fullQuery != null ? fullQuery : metaModel.getDialect().formSelect(metaModel.getTableName(), null, subQuery, orderBys, limit, offset); } if (showParameters) { StringBuilder sb = new StringBuilder(sql).append(", with parameters: "); join(sb, params, ", "); sql = sb.toString(); } return sql; } }
public class class_name { public String toSql(boolean showParameters) { String sql; if(forPaginator){ sql = metaModel.getDialect().formSelect(null, null, fullQuery, orderBys, limit, offset); // depends on control dependency: [if], data = [none] }else{ sql = fullQuery != null ? fullQuery : metaModel.getDialect().formSelect(metaModel.getTableName(), null, subQuery, orderBys, limit, offset); // depends on control dependency: [if], data = [none] } if (showParameters) { StringBuilder sb = new StringBuilder(sql).append(", with parameters: "); join(sb, params, ", "); // depends on control dependency: [if], data = [none] sql = sb.toString(); // depends on control dependency: [if], data = [none] } return sql; } }
public class class_name { private void obtainWindowBackground(@StyleRes final int themeResourceId) { TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(themeResourceId, new int[]{R.attr.materialDialogWindowBackground}); int resourceId = typedArray.getResourceId(0, 0); if (resourceId != 0) { setWindowBackground(resourceId); } else { setWindowBackground(R.drawable.material_dialog_background); } } }
public class class_name { private void obtainWindowBackground(@StyleRes final int themeResourceId) { TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(themeResourceId, new int[]{R.attr.materialDialogWindowBackground}); int resourceId = typedArray.getResourceId(0, 0); if (resourceId != 0) { setWindowBackground(resourceId); // depends on control dependency: [if], data = [(resourceId] } else { setWindowBackground(R.drawable.material_dialog_background); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected static void appendTo(@Nonnull StringBuilder buf, @Nonnull Map<? extends String, ? extends Object> values) { for (Map.Entry<? extends String, ? extends Object> e : values.entrySet()) { if (buf.length() > 0) buf.append(","); buf.append(e.getKey()); Object value = e.getValue(); if (value != null) buf.append('=').append(value); } } }
public class class_name { protected static void appendTo(@Nonnull StringBuilder buf, @Nonnull Map<? extends String, ? extends Object> values) { for (Map.Entry<? extends String, ? extends Object> e : values.entrySet()) { if (buf.length() > 0) buf.append(","); buf.append(e.getKey()); // depends on control dependency: [for], data = [e] Object value = e.getValue(); if (value != null) buf.append('=').append(value); } } }
public class class_name { public void marshall(DescribeKeyRequest describeKeyRequest, ProtocolMarshaller protocolMarshaller) { if (describeKeyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeKeyRequest.getKeyId(), KEYID_BINDING); protocolMarshaller.marshall(describeKeyRequest.getGrantTokens(), GRANTTOKENS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DescribeKeyRequest describeKeyRequest, ProtocolMarshaller protocolMarshaller) { if (describeKeyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeKeyRequest.getKeyId(), KEYID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(describeKeyRequest.getGrantTokens(), GRANTTOKENS_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 { Tag[] tags(String tagname) { ListBuffer<Tag> found = new ListBuffer<Tag>(); String target = tagname; if (target.charAt(0) != '@') { target = "@" + target; } for (Tag tag : tagList) { if (tag.kind().equals(target)) { found.append(tag); } } return found.toArray(new Tag[found.length()]); } }
public class class_name { Tag[] tags(String tagname) { ListBuffer<Tag> found = new ListBuffer<Tag>(); String target = tagname; if (target.charAt(0) != '@') { target = "@" + target; // depends on control dependency: [if], data = [none] } for (Tag tag : tagList) { if (tag.kind().equals(target)) { found.append(tag); // depends on control dependency: [if], data = [none] } } return found.toArray(new Tag[found.length()]); } }
public class class_name { public static void initMchKeyStore(String mch_id,String keyStoreFilePath){ try { initMchKeyStore(mch_id, new FileInputStream(new File(keyStoreFilePath))); } catch (FileNotFoundException e) { logger.error("init error", e); } } }
public class class_name { public static void initMchKeyStore(String mch_id,String keyStoreFilePath){ try { initMchKeyStore(mch_id, new FileInputStream(new File(keyStoreFilePath))); // depends on control dependency: [try], data = [none] } catch (FileNotFoundException e) { logger.error("init error", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); AbstractSecurityDeployer<?> deployer = null; if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { deployer = new EarSecurityDeployer(); JaccService<?> service = deployer.deploy(deploymentUnit); if (service != null) { final ServiceName jaccServiceName = deploymentUnit.getServiceName().append(JaccService.SERVICE_NAME); final ServiceTarget serviceTarget = phaseContext.getServiceTarget(); ServiceBuilder<?> builder = serviceTarget.addService(jaccServiceName, service); if (deploymentUnit.getParent() != null) { // add dependency to parent policy final DeploymentUnit parentDU = deploymentUnit.getParent(); builder.addDependency(parentDU.getServiceName().append(JaccService.SERVICE_NAME), PolicyConfiguration.class, service.getParentPolicyInjector()); } builder.setInitialMode(Mode.ACTIVE).install(); } } } }
public class class_name { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); AbstractSecurityDeployer<?> deployer = null; if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { deployer = new EarSecurityDeployer(); JaccService<?> service = deployer.deploy(deploymentUnit); if (service != null) { final ServiceName jaccServiceName = deploymentUnit.getServiceName().append(JaccService.SERVICE_NAME); final ServiceTarget serviceTarget = phaseContext.getServiceTarget(); ServiceBuilder<?> builder = serviceTarget.addService(jaccServiceName, service); if (deploymentUnit.getParent() != null) { // add dependency to parent policy final DeploymentUnit parentDU = deploymentUnit.getParent(); builder.addDependency(parentDU.getServiceName().append(JaccService.SERVICE_NAME), PolicyConfiguration.class, service.getParentPolicyInjector()); // depends on control dependency: [if], data = [none] } builder.setInitialMode(Mode.ACTIVE).install(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static Expression decodeJson(String jsonString) { try { JsonObject jsonObject = CouchbaseAsyncBucket.JSON_OBJECT_TRANSCODER.stringToJsonObject(jsonString); return decodeJson(jsonObject); } catch (Exception e) { throw new IllegalArgumentException("String is not representing JSON object: " + jsonString); } } }
public class class_name { public static Expression decodeJson(String jsonString) { try { JsonObject jsonObject = CouchbaseAsyncBucket.JSON_OBJECT_TRANSCODER.stringToJsonObject(jsonString); return decodeJson(jsonObject); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new IllegalArgumentException("String is not representing JSON object: " + jsonString); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static boolean isNumber(JsonNode node, boolean isTypeLoose) { if (node.isNumber()) { return true; } else if (isTypeLoose) { if (TypeFactory.getValueNodeType(node) == JsonType.STRING) { return isNumeric(node.textValue()); } } return false; } }
public class class_name { public static boolean isNumber(JsonNode node, boolean isTypeLoose) { if (node.isNumber()) { return true; // depends on control dependency: [if], data = [none] } else if (isTypeLoose) { if (TypeFactory.getValueNodeType(node) == JsonType.STRING) { return isNumeric(node.textValue()); // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public void printSubgraph( Node node, String lead, int depthOfSubgraph, int maxDepthOfSubgraph ) throws RepositoryException { int currentDepth = node.getDepth() - depthOfSubgraph + 1; if (currentDepth > maxDepthOfSubgraph) return; if (lead == null) lead = ""; String nodeLead = lead + createString(' ', (currentDepth - 1) * 2); StringBuilder sb = new StringBuilder(); sb.append(nodeLead); if (node.getDepth() == 0) { sb.append("/"); } else { sb.append(node.getName()); if (node.getIndex() != 1) { sb.append('[').append(node.getIndex()).append(']'); } } sb.append(" jcr:primaryType=" + node.getPrimaryNodeType().getName()); boolean referenceable = node.isNodeType("mix:referenceable"); if (node.getMixinNodeTypes().length != 0) { sb.append(" jcr:mixinTypes=["); boolean first = true; for (NodeType mixin : node.getMixinNodeTypes()) { if (first) first = false; else sb.append(','); sb.append(mixin.getName()); } sb.append(']'); } if (referenceable) { sb.append(" jcr:uuid=" + node.getIdentifier()); } print(sb); List<String> propertyNames = new LinkedList<String>(); for (PropertyIterator iter = node.getProperties(); iter.hasNext();) { Property property = iter.nextProperty(); String name = property.getName(); if (name.equals("jcr:primaryType") || name.equals("jcr:mixinTypes") || name.equals("jcr:uuid")) continue; propertyNames.add(property.getName()); } Collections.sort(propertyNames); for (String propertyName : propertyNames) { Property property = node.getProperty(propertyName); sb = new StringBuilder(); sb.append(nodeLead).append(" - ").append(propertyName).append('='); int type = property.getType(); boolean binary = type == PropertyType.BINARY; if (property.isMultiple()) { sb.append('['); boolean first = true; for (Value value : property.getValues()) { if (first) first = false; else sb.append(','); if (binary) { sb.append(value.getBinary()); } else { sb.append(getStringValue(value, type)); } } sb.append(']'); } else { Value value = property.getValue(); if (binary) { sb.append(value.getBinary()); } else { sb.append(getStringValue(value, type)); } } print(sb); } if (currentDepth < maxDepthOfSubgraph) { for (NodeIterator iter = node.getNodes(); iter.hasNext();) { Node child = iter.nextNode(); printSubgraph(child, lead, depthOfSubgraph, maxDepthOfSubgraph); } } } }
public class class_name { public void printSubgraph( Node node, String lead, int depthOfSubgraph, int maxDepthOfSubgraph ) throws RepositoryException { int currentDepth = node.getDepth() - depthOfSubgraph + 1; if (currentDepth > maxDepthOfSubgraph) return; if (lead == null) lead = ""; String nodeLead = lead + createString(' ', (currentDepth - 1) * 2); StringBuilder sb = new StringBuilder(); sb.append(nodeLead); if (node.getDepth() == 0) { sb.append("/"); } else { sb.append(node.getName()); if (node.getIndex() != 1) { sb.append('[').append(node.getIndex()).append(']'); // depends on control dependency: [if], data = [(node.getIndex()] } } sb.append(" jcr:primaryType=" + node.getPrimaryNodeType().getName()); boolean referenceable = node.isNodeType("mix:referenceable"); if (node.getMixinNodeTypes().length != 0) { sb.append(" jcr:mixinTypes=["); boolean first = true; for (NodeType mixin : node.getMixinNodeTypes()) { if (first) first = false; else sb.append(','); sb.append(mixin.getName()); } sb.append(']'); } if (referenceable) { sb.append(" jcr:uuid=" + node.getIdentifier()); } print(sb); List<String> propertyNames = new LinkedList<String>(); for (PropertyIterator iter = node.getProperties(); iter.hasNext();) { Property property = iter.nextProperty(); String name = property.getName(); if (name.equals("jcr:primaryType") || name.equals("jcr:mixinTypes") || name.equals("jcr:uuid")) continue; propertyNames.add(property.getName()); } Collections.sort(propertyNames); for (String propertyName : propertyNames) { Property property = node.getProperty(propertyName); sb = new StringBuilder(); sb.append(nodeLead).append(" - ").append(propertyName).append('='); int type = property.getType(); boolean binary = type == PropertyType.BINARY; if (property.isMultiple()) { sb.append('['); // depends on control dependency: [if], data = [none] boolean first = true; for (Value value : property.getValues()) { if (first) first = false; else sb.append(','); if (binary) { sb.append(value.getBinary()); // depends on control dependency: [if], data = [none] } else { sb.append(getStringValue(value, type)); // depends on control dependency: [if], data = [none] } } sb.append(']'); // depends on control dependency: [if], data = [none] } else { Value value = property.getValue(); if (binary) { sb.append(value.getBinary()); // depends on control dependency: [if], data = [none] } else { sb.append(getStringValue(value, type)); // depends on control dependency: [if], data = [none] } } print(sb); } if (currentDepth < maxDepthOfSubgraph) { for (NodeIterator iter = node.getNodes(); iter.hasNext();) { Node child = iter.nextNode(); printSubgraph(child, lead, depthOfSubgraph, maxDepthOfSubgraph); } } } }
public class class_name { List<DataSlice> flatten(Object store, byte[] nameBytes) throws MessageEncodeFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "flatten", new Object[] {store, nameBytes}); // Initial capacity is sufficient for a 2 part message List<DataSlice> messageSlices = new ArrayList<DataSlice>(3); /* If we have a message store we need to ensure it contains all the */ /* schema defintions needed to be able decode this message sometime later */ long[] encodeIds; if (store != null) { if (!(store instanceof MessageStore)) { throw new IllegalArgumentException("store is not a MessageStore instance"); } JMFSchema[] encodeSchemas = getEncodingSchemas(); SchemaStore.saveSchemas((MessageStore)store, encodeSchemas); encodeIds = new long[encodeSchemas.length]; for (int i = 0; i < encodeSchemas.length; i++) { encodeIds[i] = encodeSchemas[i].getID(); } } else { encodeIds = new long[0]; } // Write the first slice - this just contains name & ids information int bufferLength = 0; bufferLength += ArrayUtil.INT_SIZE; bufferLength += nameBytes.length; bufferLength += ArrayUtil.INT_SIZE; bufferLength += encodeIds.length * ArrayUtil.LONG_SIZE; bufferLength += IDS_LENGTH; // for the top-level versions & schema ids bufferLength += ArrayUtil.INT_SIZE; // for the length of the header part byte[] buff0 = new byte[bufferLength]; int offset = 0; ArrayUtil.writeInt(buff0, offset, nameBytes.length); // the length of the class name offset += ArrayUtil.INT_SIZE; ArrayUtil.writeBytes(buff0, offset, nameBytes); // the class name offset += nameBytes.length; ArrayUtil.writeInt(buff0, offset, encodeIds.length); // the number of encoding schema ids offset += ArrayUtil.INT_SIZE; for (int i = 0; i < encodeIds.length; i++) { ArrayUtil.writeLong(buff0, offset, encodeIds[i]); // each encoding schema id offset += ArrayUtil.LONG_SIZE; } // Write the top-level Schema Ids & their versions to the buffer & wrap it in a DataSlice offset += encodeIds(buff0, offset); DataSlice slice0 = new DataSlice(buff0, 0, bufferLength); try { // We need to lock the message around the call to updateDataFields() and the // actual encode of the part(s), so that noone can update any JMF message data // during that time (because they can not get the hdr2, api, or payload part). // Otherwise it is possible to get an inconsistent view of the message with some updates // included but those to the cached values 'missing'. // It is still strictly possible for the top-level schema header fields to be // updated, but this will not happen to any fields visible to an app. synchronized(theMessage) { // Next ensure any cached message data is written back before we get the // low level (JSMessageImpl) locks d364050 theMessage.updateDataFields(MfpConstants.UDF_FLATTEN); DataSlice slice1 = null; DataSlice slice2 = null; // Write the second slice - this contains the header slice1 = encodeHeaderPartToSlice(headerPart); // Now we have to tell the buffer in the slice0 how long the header part is ArrayUtil.writeInt(buff0, offset, slice1.getLength()); // Now the first 2 slices are complete we can put them in the list. // Slices must be added in the correct order. messageSlices.add(slice0); messageSlices.add(slice1); // Now for the 3rd slice, which will contain the payload (if there is one) if (payloadPart != null) { slice2 = encodePayloadPartToSlice(payloadPart, null); messageSlices.add(slice2); } } } catch (MessageEncodeFailedException e1) { // This will have been thrown by encodeXxxxxPartToSlice() which will // already have dumped the appropriate message part. FFDCFilter.processException(e1, "com.ibm.ws.sib.mfp.impl.JsMsgObject.flatten", "jmo580", this, new Object[] { MfpConstants.DM_MESSAGE, null, theMessage }); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "flatten failed: " + e1); throw e1; } catch (Exception e) { // Not sure this can ever happen, but if it does dump the whole message. FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsMsgObject.flatten", "jmo590", this, new Object[] { new Object[] { MfpConstants.DM_MESSAGE, headerPart.jmfPart, theMessage }, new Object[] { MfpConstants.DM_MESSAGE, payloadPart.jmfPart, theMessage } } ); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "flatten failed: " + e); throw new MessageEncodeFailedException(e); } // If debug trace, dump the message & slices before returning if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Flattened JMF Message", debugMsg()); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Message DataSlices: ", SibTr.formatSlices(messageSlices, MfpDiagnostics.getDiagnosticDataLimitInt())); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "flatten"); return messageSlices; } }
public class class_name { List<DataSlice> flatten(Object store, byte[] nameBytes) throws MessageEncodeFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "flatten", new Object[] {store, nameBytes}); // Initial capacity is sufficient for a 2 part message List<DataSlice> messageSlices = new ArrayList<DataSlice>(3); /* If we have a message store we need to ensure it contains all the */ /* schema defintions needed to be able decode this message sometime later */ long[] encodeIds; if (store != null) { if (!(store instanceof MessageStore)) { throw new IllegalArgumentException("store is not a MessageStore instance"); } JMFSchema[] encodeSchemas = getEncodingSchemas(); SchemaStore.saveSchemas((MessageStore)store, encodeSchemas); encodeIds = new long[encodeSchemas.length]; for (int i = 0; i < encodeSchemas.length; i++) { encodeIds[i] = encodeSchemas[i].getID(); } } else { encodeIds = new long[0]; } // Write the first slice - this just contains name & ids information int bufferLength = 0; bufferLength += ArrayUtil.INT_SIZE; bufferLength += nameBytes.length; bufferLength += ArrayUtil.INT_SIZE; bufferLength += encodeIds.length * ArrayUtil.LONG_SIZE; bufferLength += IDS_LENGTH; // for the top-level versions & schema ids bufferLength += ArrayUtil.INT_SIZE; // for the length of the header part byte[] buff0 = new byte[bufferLength]; int offset = 0; ArrayUtil.writeInt(buff0, offset, nameBytes.length); // the length of the class name offset += ArrayUtil.INT_SIZE; ArrayUtil.writeBytes(buff0, offset, nameBytes); // the class name offset += nameBytes.length; ArrayUtil.writeInt(buff0, offset, encodeIds.length); // the number of encoding schema ids offset += ArrayUtil.INT_SIZE; for (int i = 0; i < encodeIds.length; i++) { ArrayUtil.writeLong(buff0, offset, encodeIds[i]); // each encoding schema id offset += ArrayUtil.LONG_SIZE; } // Write the top-level Schema Ids & their versions to the buffer & wrap it in a DataSlice offset += encodeIds(buff0, offset); DataSlice slice0 = new DataSlice(buff0, 0, bufferLength); try { // We need to lock the message around the call to updateDataFields() and the // actual encode of the part(s), so that noone can update any JMF message data // during that time (because they can not get the hdr2, api, or payload part). // Otherwise it is possible to get an inconsistent view of the message with some updates // included but those to the cached values 'missing'. // It is still strictly possible for the top-level schema header fields to be // updated, but this will not happen to any fields visible to an app. synchronized(theMessage) { // Next ensure any cached message data is written back before we get the // low level (JSMessageImpl) locks d364050 theMessage.updateDataFields(MfpConstants.UDF_FLATTEN); DataSlice slice1 = null; DataSlice slice2 = null; // Write the second slice - this contains the header slice1 = encodeHeaderPartToSlice(headerPart); // Now we have to tell the buffer in the slice0 how long the header part is ArrayUtil.writeInt(buff0, offset, slice1.getLength()); // Now the first 2 slices are complete we can put them in the list. // Slices must be added in the correct order. messageSlices.add(slice0); messageSlices.add(slice1); // Now for the 3rd slice, which will contain the payload (if there is one) if (payloadPart != null) { slice2 = encodePayloadPartToSlice(payloadPart, null); // depends on control dependency: [if], data = [(payloadPart] messageSlices.add(slice2); // depends on control dependency: [if], data = [none] } } } catch (MessageEncodeFailedException e1) { // This will have been thrown by encodeXxxxxPartToSlice() which will // already have dumped the appropriate message part. FFDCFilter.processException(e1, "com.ibm.ws.sib.mfp.impl.JsMsgObject.flatten", "jmo580", this, new Object[] { MfpConstants.DM_MESSAGE, null, theMessage }); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "flatten failed: " + e1); throw e1; } catch (Exception e) { // Not sure this can ever happen, but if it does dump the whole message. FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsMsgObject.flatten", "jmo590", this, new Object[] { new Object[] { MfpConstants.DM_MESSAGE, headerPart.jmfPart, theMessage }, new Object[] { MfpConstants.DM_MESSAGE, payloadPart.jmfPart, theMessage } } ); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "flatten failed: " + e); throw new MessageEncodeFailedException(e); } // If debug trace, dump the message & slices before returning if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Flattened JMF Message", debugMsg()); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Message DataSlices: ", SibTr.formatSlices(messageSlices, MfpDiagnostics.getDiagnosticDataLimitInt())); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "flatten"); return messageSlices; } }
public class class_name { public final synchronized void destroyNotRemove() { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) // d144064 Tr.entry(tc, "destroyNotRemove : " + this); if (state == DESTROYED) { return; } // If running in an extended persistence context, the JEERuntime code // maintains a map of SFSBs that must be cleaned up. This is // especially important if this method is called due to a timeout. // PM12927 if (ivExPcContext != null) { container.getEJBRuntime().getEJBJPAContainer().onRemoveOrDiscard(ivExPcContext); } if (isZOS) { removeServantRoutingAffinity(); // d646413.2 } setState(DESTROYED); // Release any JCDI creational contexts that may exist. F743-29174 releaseManagedObjectContext(); if (pmiBean != null) { pmiBean.beanDestroyed(); } disconnectWrapper(); // F61004.6 destroyHandleList(); if (isTraceOn && tc.isEntryEnabled()) // d144064 Tr.exit(tc, "destroyNotRemove"); } }
public class class_name { public final synchronized void destroyNotRemove() { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) // d144064 Tr.entry(tc, "destroyNotRemove : " + this); if (state == DESTROYED) { return; // depends on control dependency: [if], data = [none] } // If running in an extended persistence context, the JEERuntime code // maintains a map of SFSBs that must be cleaned up. This is // especially important if this method is called due to a timeout. // PM12927 if (ivExPcContext != null) { container.getEJBRuntime().getEJBJPAContainer().onRemoveOrDiscard(ivExPcContext); // depends on control dependency: [if], data = [(ivExPcContext] } if (isZOS) { removeServantRoutingAffinity(); // d646413.2 // depends on control dependency: [if], data = [none] } setState(DESTROYED); // Release any JCDI creational contexts that may exist. F743-29174 releaseManagedObjectContext(); if (pmiBean != null) { pmiBean.beanDestroyed(); // depends on control dependency: [if], data = [none] } disconnectWrapper(); // F61004.6 destroyHandleList(); if (isTraceOn && tc.isEntryEnabled()) // d144064 Tr.exit(tc, "destroyNotRemove"); } }
public class class_name { protected Session getWriteSession() { final Session session = getSession(); if (session.isDefaultReadOnly()) { throw new ReadOnlyTransactionException("Cannot perform write operation on " + clazz + " in a read-only transaction"); } else { return session; } } }
public class class_name { protected Session getWriteSession() { final Session session = getSession(); if (session.isDefaultReadOnly()) { throw new ReadOnlyTransactionException("Cannot perform write operation on " + clazz + " in a read-only transaction"); } else { return session; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(DeleteDynamicThingGroupRequest deleteDynamicThingGroupRequest, ProtocolMarshaller protocolMarshaller) { if (deleteDynamicThingGroupRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteDynamicThingGroupRequest.getThingGroupName(), THINGGROUPNAME_BINDING); protocolMarshaller.marshall(deleteDynamicThingGroupRequest.getExpectedVersion(), EXPECTEDVERSION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DeleteDynamicThingGroupRequest deleteDynamicThingGroupRequest, ProtocolMarshaller protocolMarshaller) { if (deleteDynamicThingGroupRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteDynamicThingGroupRequest.getThingGroupName(), THINGGROUPNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(deleteDynamicThingGroupRequest.getExpectedVersion(), EXPECTEDVERSION_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 { private boolean validateDigits(Object validationObject, Annotation annotate) { if (checkNullObject(validationObject)) { return true; } if (checkvalidDigitTypes(validationObject.getClass())) { if (!NumberUtils.isDigits(toString(validationObject))) { throwValidationException(((Digits) annotate).message()); } } return true; } }
public class class_name { private boolean validateDigits(Object validationObject, Annotation annotate) { if (checkNullObject(validationObject)) { return true; // depends on control dependency: [if], data = [none] } if (checkvalidDigitTypes(validationObject.getClass())) { if (!NumberUtils.isDigits(toString(validationObject))) { throwValidationException(((Digits) annotate).message()); // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { public java.util.List<ListenerDescription> getListenerDescriptions() { if (listenerDescriptions == null) { listenerDescriptions = new com.amazonaws.internal.SdkInternalList<ListenerDescription>(); } return listenerDescriptions; } }
public class class_name { public java.util.List<ListenerDescription> getListenerDescriptions() { if (listenerDescriptions == null) { listenerDescriptions = new com.amazonaws.internal.SdkInternalList<ListenerDescription>(); // depends on control dependency: [if], data = [none] } return listenerDescriptions; } }
public class class_name { public static final Point[] midPoints(int count, Point p1, Point p2) { Point[] res = new Point[count]; Point gap = AbstractPoint.subtract(p2, p1); Point leg = AbstractPoint.mul((double)(1)/(double)(count+1), gap); for (int ii=0;ii<count;ii++) { res[ii] = AbstractPoint.add(p1, AbstractPoint.mul(ii+1, leg)); } return res; } }
public class class_name { public static final Point[] midPoints(int count, Point p1, Point p2) { Point[] res = new Point[count]; Point gap = AbstractPoint.subtract(p2, p1); Point leg = AbstractPoint.mul((double)(1)/(double)(count+1), gap); for (int ii=0;ii<count;ii++) { res[ii] = AbstractPoint.add(p1, AbstractPoint.mul(ii+1, leg)); // depends on control dependency: [for], data = [ii] } return res; } }
public class class_name { @Override public EClass getIfcTask() { if (ifcTaskEClass == null) { ifcTaskEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(700); } return ifcTaskEClass; } }
public class class_name { @Override public EClass getIfcTask() { if (ifcTaskEClass == null) { ifcTaskEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(700); // depends on control dependency: [if], data = [none] } return ifcTaskEClass; } }
public class class_name { public JtxTransaction getTransaction() { ArrayList<JtxTransaction> txlist = txStack.get(); if (txlist == null) { return null; } if (txlist.isEmpty()) { return null; } return txlist.get(txlist.size() - 1); // get last } }
public class class_name { public JtxTransaction getTransaction() { ArrayList<JtxTransaction> txlist = txStack.get(); if (txlist == null) { return null; // depends on control dependency: [if], data = [none] } if (txlist.isEmpty()) { return null; // depends on control dependency: [if], data = [none] } return txlist.get(txlist.size() - 1); // get last } }
public class class_name { @Override public String skipToken() { int length = sql.length(); int endIndex = length; char quote = position < length ? sql.charAt(position) : '\0'; boolean quoting = quote == '\'' || quote == '('; if (quote == '(') { quote = ')'; } for (int i = quoting ? position + 1 : position; i < length; ++i) { char c = sql.charAt(i); if ((Character.isWhitespace(c) || c == ',' || c == ')' || c == '(') && !quoting) { endIndex = i; break; } else if (c == '/' && i + 1 < length && sql.charAt(i + 1) == '*') { endIndex = i; break; } else if (c == '-' && i + 1 < length && sql.charAt(i + 1) == '-') { endIndex = i; break; } else if (quoting && quote == '\'' && c == '\'' && (i + 1 >= length || sql.charAt(i + 1) != '\'')) { endIndex = i + 1; break; } else if (quoting && c == quote) { endIndex = i + 1; break; } } token = sql.substring(position, endIndex); tokenType = TokenType.SQL; nextTokenType = TokenType.SQL; position = endIndex; return token; } }
public class class_name { @Override public String skipToken() { int length = sql.length(); int endIndex = length; char quote = position < length ? sql.charAt(position) : '\0'; boolean quoting = quote == '\'' || quote == '('; if (quote == '(') { quote = ')'; // depends on control dependency: [if], data = [none] } for (int i = quoting ? position + 1 : position; i < length; ++i) { char c = sql.charAt(i); if ((Character.isWhitespace(c) || c == ',' || c == ')' || c == '(') && !quoting) { endIndex = i; // depends on control dependency: [if], data = [none] break; } else if (c == '/' && i + 1 < length && sql.charAt(i + 1) == '*') { endIndex = i; // depends on control dependency: [if], data = [none] break; } else if (c == '-' && i + 1 < length && sql.charAt(i + 1) == '-') { endIndex = i; // depends on control dependency: [if], data = [none] break; } else if (quoting && quote == '\'' && c == '\'' && (i + 1 >= length || sql.charAt(i + 1) != '\'')) { endIndex = i + 1; // depends on control dependency: [if], data = [none] break; } else if (quoting && c == quote) { endIndex = i + 1; // depends on control dependency: [if], data = [none] break; } } token = sql.substring(position, endIndex); tokenType = TokenType.SQL; nextTokenType = TokenType.SQL; position = endIndex; return token; } }
public class class_name { private static String expand(final String value) { // shortcut if value does not contain any properties if (value.contains("${") == false) { return value; } // return AccessController.doPrivileged(new PrivilegedAction<String>() { // public String run() { try { return PropertyExpander.expand(value); } catch (GeneralSecurityException e) { throw new ProviderException(e); } // } // }); } }
public class class_name { private static String expand(final String value) { // shortcut if value does not contain any properties if (value.contains("${") == false) { return value; // depends on control dependency: [if], data = [none] } // return AccessController.doPrivileged(new PrivilegedAction<String>() { // public String run() { try { return PropertyExpander.expand(value); // depends on control dependency: [try], data = [none] } catch (GeneralSecurityException e) { throw new ProviderException(e); } // depends on control dependency: [catch], data = [none] // } // }); } }
public class class_name { public RgbaColor[] getPaletteVaryLightness(int count) { // a max of 80 and an offset of 10 keeps us away from the // edges float[] spread = getSpreadInRange(l(), count, 80, 10); RgbaColor[] ret = new RgbaColor[count]; for (int i = 0; i < count; i++) { ret[i] = withLightness(spread[i]); } return ret; } }
public class class_name { public RgbaColor[] getPaletteVaryLightness(int count) { // a max of 80 and an offset of 10 keeps us away from the // edges float[] spread = getSpreadInRange(l(), count, 80, 10); RgbaColor[] ret = new RgbaColor[count]; for (int i = 0; i < count; i++) { ret[i] = withLightness(spread[i]); // depends on control dependency: [for], data = [i] } return ret; } }
public class class_name { public List<CmsOrganizationalUnit> getOrgUnitsForRole(CmsDbContext dbc, CmsRole role, boolean includeSubOus) throws CmsException { String ouFqn = role.getOuFqn(); if (ouFqn == null) { ouFqn = ""; role = role.forOrgUnit(""); } CmsOrganizationalUnit ou = readOrganizationalUnit(dbc, ouFqn); List<CmsOrganizationalUnit> orgUnits = new ArrayList<CmsOrganizationalUnit>(); if (m_securityManager.hasRole(dbc, dbc.currentUser(), role)) { orgUnits.add(ou); } if (includeSubOus) { Iterator<CmsOrganizationalUnit> it = getOrganizationalUnits(dbc, ou, true).iterator(); while (it.hasNext()) { CmsOrganizationalUnit orgUnit = it.next(); if (m_securityManager.hasRole(dbc, dbc.currentUser(), role.forOrgUnit(orgUnit.getName()))) { orgUnits.add(orgUnit); } } } return orgUnits; } }
public class class_name { public List<CmsOrganizationalUnit> getOrgUnitsForRole(CmsDbContext dbc, CmsRole role, boolean includeSubOus) throws CmsException { String ouFqn = role.getOuFqn(); if (ouFqn == null) { ouFqn = ""; role = role.forOrgUnit(""); } CmsOrganizationalUnit ou = readOrganizationalUnit(dbc, ouFqn); List<CmsOrganizationalUnit> orgUnits = new ArrayList<CmsOrganizationalUnit>(); if (m_securityManager.hasRole(dbc, dbc.currentUser(), role)) { orgUnits.add(ou); } if (includeSubOus) { Iterator<CmsOrganizationalUnit> it = getOrganizationalUnits(dbc, ou, true).iterator(); while (it.hasNext()) { CmsOrganizationalUnit orgUnit = it.next(); if (m_securityManager.hasRole(dbc, dbc.currentUser(), role.forOrgUnit(orgUnit.getName()))) { orgUnits.add(orgUnit); // depends on control dependency: [if], data = [none] } } } return orgUnits; } }
public class class_name { private long[][] findDimensions(ArrayDBIDs medoids, Relation<V> database, DistanceQuery<V> distFunc, RangeQuery<V> rangeQuery) { // get localities DataStore<DBIDs> localities = getLocalities(medoids, distFunc, rangeQuery); // compute x_ij = avg distance from points in l_i to medoid m_i final int dim = RelationUtil.dimensionality(database); final int numc = medoids.size(); double[][] averageDistances = new double[numc][]; for(DBIDArrayIter iter = medoids.iter(); iter.valid(); iter.advance()) { V medoid_i = database.get(iter); DBIDs l_i = localities.get(iter); double[] x_i = new double[dim]; for(DBIDIter qr = l_i.iter(); qr.valid(); qr.advance()) { V o = database.get(qr); for(int d = 0; d < dim; d++) { x_i[d] += Math.abs(medoid_i.doubleValue(d) - o.doubleValue(d)); } } for(int d = 0; d < dim; d++) { x_i[d] /= l_i.size(); } averageDistances[iter.getOffset()] = x_i; } List<DoubleIntInt> z_ijs = computeZijs(averageDistances, dim); return computeDimensionMap(z_ijs, dim, numc); } }
public class class_name { private long[][] findDimensions(ArrayDBIDs medoids, Relation<V> database, DistanceQuery<V> distFunc, RangeQuery<V> rangeQuery) { // get localities DataStore<DBIDs> localities = getLocalities(medoids, distFunc, rangeQuery); // compute x_ij = avg distance from points in l_i to medoid m_i final int dim = RelationUtil.dimensionality(database); final int numc = medoids.size(); double[][] averageDistances = new double[numc][]; for(DBIDArrayIter iter = medoids.iter(); iter.valid(); iter.advance()) { V medoid_i = database.get(iter); DBIDs l_i = localities.get(iter); double[] x_i = new double[dim]; for(DBIDIter qr = l_i.iter(); qr.valid(); qr.advance()) { V o = database.get(qr); for(int d = 0; d < dim; d++) { x_i[d] += Math.abs(medoid_i.doubleValue(d) - o.doubleValue(d)); // depends on control dependency: [for], data = [d] } } for(int d = 0; d < dim; d++) { x_i[d] /= l_i.size(); // depends on control dependency: [for], data = [d] } averageDistances[iter.getOffset()] = x_i; // depends on control dependency: [for], data = [iter] } List<DoubleIntInt> z_ijs = computeZijs(averageDistances, dim); return computeDimensionMap(z_ijs, dim, numc); } }
public class class_name { public boolean isModifiedOnVersion(String version) { if (version == null || version.isEmpty()) { return true; } if (this.history != null && this.history.isModifiedOnVersion(version)) { return true; } if (this.fields != null) { for (APIParameter param : this.fields) { if (param.isModifiedOnVersion(version)) { return true; } } } return false; } }
public class class_name { public boolean isModifiedOnVersion(String version) { if (version == null || version.isEmpty()) { return true; // depends on control dependency: [if], data = [none] } if (this.history != null && this.history.isModifiedOnVersion(version)) { return true; // depends on control dependency: [if], data = [none] } if (this.fields != null) { for (APIParameter param : this.fields) { if (param.isModifiedOnVersion(version)) { return true; // depends on control dependency: [if], data = [none] } } } return false; } }
public class class_name { private LinkedList<Object> OperatorTree(Queue<Object> rpn){ LinkedList<Object> operand = new LinkedList<Object>(); while(!rpn.isEmpty()){ if(rpn.peek() instanceof Operator){ Operator opt = (Operator) rpn.poll(); opt.wrap(operand); operand.addFirst(opt); continue; } if(rpn.peek() instanceof Elobj){ ((Elobj) rpn.peek()).setEc(ec); } operand.addFirst(rpn.poll()); } return operand; } }
public class class_name { private LinkedList<Object> OperatorTree(Queue<Object> rpn){ LinkedList<Object> operand = new LinkedList<Object>(); while(!rpn.isEmpty()){ if(rpn.peek() instanceof Operator){ Operator opt = (Operator) rpn.poll(); opt.wrap(operand); // depends on control dependency: [if], data = [none] operand.addFirst(opt); // depends on control dependency: [if], data = [none] continue; } if(rpn.peek() instanceof Elobj){ ((Elobj) rpn.peek()).setEc(ec); // depends on control dependency: [if], data = [none] } operand.addFirst(rpn.poll()); // depends on control dependency: [while], data = [none] } return operand; } }
public class class_name { public static final void getActivitySessions(ActivitySessionAttribute[] asAttrs, int type, String[] methodNames, Class<?>[][] methodParamTypes, List<ActivitySessionMethod> asAttrList, String ejbName, boolean usesBeanManagedAS) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "getActivitySessions", (Object[])asAttrs); if (!usesBeanManagedAS) { // d127328 if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Bean is CMAS"); if (asAttrList != null) { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "asAttrList non-null"); // array to keep track of what kind of style last set the method-specific behavior int[] highestStyleOnMethod = new int[methodNames.length]; // Elements of highestStyleOnMethod[] are initialized to zero by Java rules. // i : asAttrList loop // j : MethodElements loop // k : Method loop for (int i = 0; i < asAttrList.size(); ++i) { ActivitySessionMethod asMethod = asAttrList.get(i); ActivitySessionAttribute asAttr = asMethod.getActivitySessionAttribute(); @SuppressWarnings("unchecked") List<com.ibm.ws.javaee.dd.ejb.Method> methodElements = asMethod.getMethodElements(); for (int j = 0; j < methodElements.size(); ++j) { com.ibm.ws.javaee.dd.ejb.Method me = methodElements.get(j); if (isTraceOn && tc.isDebugEnabled()) { trace(me, me.getInterfaceTypeValue() == com.ibm.ws.javaee.dd.ejb.Method.INTERFACE_TYPE_UNSPECIFIED ? "Interface type unspecified" : "Interface type: " + me.getInterfaceTypeValue()); } // Is this method element for the bean we are processing? if ((me.getEnterpriseBeanName()).equals(ejbName)) { String meName = me.getMethodName().trim(); int meType = me.getInterfaceTypeValue(); if (meName.equals("*")) { if (meType == com.ibm.ws.javaee.dd.ejb.Method.INTERFACE_TYPE_UNSPECIFIED) { // style type 1 -- wildcard on all bean methods if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Style type 1 - all bean methods:", asAttr); for (int k = 0; k < methodNames.length; ++k) { if (highestStyleOnMethod[k] <= 1) { asAttrs[k] = asAttr; highestStyleOnMethod[k] = 1; } } } else if (meType == type) { //LIDB2257.19 // style type 2 -- wildcard on home or remote interface methods if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Style type 2 - home/remote methods only:", asAttr); for (int k = 0; k < methodNames.length; ++k) { if (highestStyleOnMethod[k] <= 2) { asAttrs[k] = asAttr; highestStyleOnMethod[k] = 2; } } } } else if (meType == com.ibm.ws.javaee.dd.ejb.Method.INTERFACE_TYPE_UNSPECIFIED || meType == type) { //LIDB2257.19 // It is not a wildcard, and either has an unspecified // type, or is of the right type (Remote/Home/Local), // so check for a method name match. d123321 for (int k = 0; k < methodNames.length; ++k) { if (meName.equals(methodNames[k])) { List<String> meParms = me.getMethodParamList(); if (meParms == null) { // style type 3 - matching method name, no signature // specified if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Style type 3 - method name only:", asAttr); if (highestStyleOnMethod[k] <= 3) { asAttrs[k] = asAttr; highestStyleOnMethod[k] = 3; } } else { if (DDUtil.methodParamsMatch(meParms, methodParamTypes[k])) { // style type 4 - matching method name and signature if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Style type 4 - method name and signature:", asAttr); asAttrs[k] = asAttr; highestStyleOnMethod[k] = 4; } // method parms match specified parms } // method parms were specified } // methodExtension name matches method name } // method loop (k) } // if/then/else for meName='*' } // enterpriseBean name matches parm in methodExtension } // methodElements loop (j) } // asAttrList loop (i) } // asAttrList != null } else if (usesBeanManagedAS) { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Bean is BMAS -- all methods will be set to AS_BEAN_MANAGED"); for (int i = 0; i < asAttrs.length; i++) { asAttrs[i] = ActivitySessionAttribute.AS_BEAN_MANAGED; } } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(tc, "getActivitySessions"); return; } }
public class class_name { public static final void getActivitySessions(ActivitySessionAttribute[] asAttrs, int type, String[] methodNames, Class<?>[][] methodParamTypes, List<ActivitySessionMethod> asAttrList, String ejbName, boolean usesBeanManagedAS) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "getActivitySessions", (Object[])asAttrs); if (!usesBeanManagedAS) { // d127328 if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Bean is CMAS"); if (asAttrList != null) { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "asAttrList non-null"); // array to keep track of what kind of style last set the method-specific behavior int[] highestStyleOnMethod = new int[methodNames.length]; // Elements of highestStyleOnMethod[] are initialized to zero by Java rules. // i : asAttrList loop // j : MethodElements loop // k : Method loop for (int i = 0; i < asAttrList.size(); ++i) { ActivitySessionMethod asMethod = asAttrList.get(i); ActivitySessionAttribute asAttr = asMethod.getActivitySessionAttribute(); @SuppressWarnings("unchecked") List<com.ibm.ws.javaee.dd.ejb.Method> methodElements = asMethod.getMethodElements(); for (int j = 0; j < methodElements.size(); ++j) { com.ibm.ws.javaee.dd.ejb.Method me = methodElements.get(j); if (isTraceOn && tc.isDebugEnabled()) { trace(me, me.getInterfaceTypeValue() == com.ibm.ws.javaee.dd.ejb.Method.INTERFACE_TYPE_UNSPECIFIED ? "Interface type unspecified" : "Interface type: " + me.getInterfaceTypeValue()); // depends on control dependency: [if], data = [none] } // Is this method element for the bean we are processing? if ((me.getEnterpriseBeanName()).equals(ejbName)) { String meName = me.getMethodName().trim(); int meType = me.getInterfaceTypeValue(); if (meName.equals("*")) { if (meType == com.ibm.ws.javaee.dd.ejb.Method.INTERFACE_TYPE_UNSPECIFIED) { // style type 1 -- wildcard on all bean methods if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Style type 1 - all bean methods:", asAttr); for (int k = 0; k < methodNames.length; ++k) { if (highestStyleOnMethod[k] <= 1) { asAttrs[k] = asAttr; // depends on control dependency: [if], data = [none] highestStyleOnMethod[k] = 1; // depends on control dependency: [if], data = [none] } } } else if (meType == type) { //LIDB2257.19 // style type 2 -- wildcard on home or remote interface methods if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Style type 2 - home/remote methods only:", asAttr); for (int k = 0; k < methodNames.length; ++k) { if (highestStyleOnMethod[k] <= 2) { asAttrs[k] = asAttr; // depends on control dependency: [if], data = [none] highestStyleOnMethod[k] = 2; // depends on control dependency: [if], data = [none] } } } } else if (meType == com.ibm.ws.javaee.dd.ejb.Method.INTERFACE_TYPE_UNSPECIFIED || meType == type) { //LIDB2257.19 // It is not a wildcard, and either has an unspecified // type, or is of the right type (Remote/Home/Local), // so check for a method name match. d123321 for (int k = 0; k < methodNames.length; ++k) { if (meName.equals(methodNames[k])) { List<String> meParms = me.getMethodParamList(); if (meParms == null) { // style type 3 - matching method name, no signature // specified if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Style type 3 - method name only:", asAttr); if (highestStyleOnMethod[k] <= 3) { asAttrs[k] = asAttr; // depends on control dependency: [if], data = [none] highestStyleOnMethod[k] = 3; // depends on control dependency: [if], data = [none] } } else { if (DDUtil.methodParamsMatch(meParms, methodParamTypes[k])) { // style type 4 - matching method name and signature if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Style type 4 - method name and signature:", asAttr); asAttrs[k] = asAttr; // depends on control dependency: [if], data = [none] highestStyleOnMethod[k] = 4; // depends on control dependency: [if], data = [none] } // method parms match specified parms } // method parms were specified } // methodExtension name matches method name } // method loop (k) } // if/then/else for meName='*' } // enterpriseBean name matches parm in methodExtension } // methodElements loop (j) } // asAttrList loop (i) } // asAttrList != null } else if (usesBeanManagedAS) { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "Bean is BMAS -- all methods will be set to AS_BEAN_MANAGED"); for (int i = 0; i < asAttrs.length; i++) { asAttrs[i] = ActivitySessionAttribute.AS_BEAN_MANAGED; // depends on control dependency: [for], data = [i] } } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(tc, "getActivitySessions"); return; } }
public class class_name { public void marshall(GeoMatchConstraint geoMatchConstraint, ProtocolMarshaller protocolMarshaller) { if (geoMatchConstraint == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(geoMatchConstraint.getType(), TYPE_BINDING); protocolMarshaller.marshall(geoMatchConstraint.getValue(), VALUE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GeoMatchConstraint geoMatchConstraint, ProtocolMarshaller protocolMarshaller) { if (geoMatchConstraint == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(geoMatchConstraint.getType(), TYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(geoMatchConstraint.getValue(), VALUE_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 invalidateDisk() { if (!diskMode.equals(DualCacheDiskMode.DISABLE)) { try { dualCacheLock.lockFullDiskWrite(); diskLruCache.delete(); openDiskLruCache(diskCacheFolder); } catch (IOException e) { logger.logError(e); } finally { dualCacheLock.unLockFullDiskWrite(); } } } }
public class class_name { public void invalidateDisk() { if (!diskMode.equals(DualCacheDiskMode.DISABLE)) { try { dualCacheLock.lockFullDiskWrite(); // depends on control dependency: [try], data = [none] diskLruCache.delete(); // depends on control dependency: [try], data = [none] openDiskLruCache(diskCacheFolder); // depends on control dependency: [try], data = [none] } catch (IOException e) { logger.logError(e); } finally { // depends on control dependency: [catch], data = [none] dualCacheLock.unLockFullDiskWrite(); } } } }
public class class_name { private CompletableFuture<Void> listen() { CompletableFuture<Void> future = new CompletableFuture<>(); context.getThreadContext().executor().execute(() -> { internalServer.listen(cluster().member().serverAddress(), context::connectServer).whenComplete((internalResult, internalError) -> { if (internalError == null) { // If the client address is different than the server address, start a separate client server. if (clientServer != null) { clientServer.listen(cluster().member().clientAddress(), context::connectClient).whenComplete((clientResult, clientError) -> { started = true; future.complete(null); }); } else { started = true; future.complete(null); } } else { future.completeExceptionally(internalError); } }); }); return future; } }
public class class_name { private CompletableFuture<Void> listen() { CompletableFuture<Void> future = new CompletableFuture<>(); context.getThreadContext().executor().execute(() -> { internalServer.listen(cluster().member().serverAddress(), context::connectServer).whenComplete((internalResult, internalError) -> { if (internalError == null) { // If the client address is different than the server address, start a separate client server. if (clientServer != null) { clientServer.listen(cluster().member().clientAddress(), context::connectClient).whenComplete((clientResult, clientError) -> { started = true; // depends on control dependency: [if], data = [none] future.complete(null); // depends on control dependency: [if], data = [null)] }); } else { started = true; future.complete(null); } } else { future.completeExceptionally(internalError); } }); }); return future; } }
public class class_name { @Override protected ModelNode convertParameterExpressions(ModelNode parameter) { ModelNode result = parameter; List<ModelNode> asList; try { asList = parameter.asList(); } catch (IllegalArgumentException iae) { // We can't convert; we'll just return parameter asList = null; } if (asList != null) { boolean changeMade = false; ModelNode newList = new ModelNode().setEmptyList(); for (ModelNode item : asList) { ModelNode converted = convertParameterElementExpressions(item); newList.add(converted); changeMade |= !converted.equals(item); } if (changeMade) { result = newList; } } return result; } }
public class class_name { @Override protected ModelNode convertParameterExpressions(ModelNode parameter) { ModelNode result = parameter; List<ModelNode> asList; try { asList = parameter.asList(); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException iae) { // We can't convert; we'll just return parameter asList = null; } // depends on control dependency: [catch], data = [none] if (asList != null) { boolean changeMade = false; ModelNode newList = new ModelNode().setEmptyList(); for (ModelNode item : asList) { ModelNode converted = convertParameterElementExpressions(item); newList.add(converted); // depends on control dependency: [for], data = [none] changeMade |= !converted.equals(item); // depends on control dependency: [for], data = [item] } if (changeMade) { result = newList; // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public Map<String, String> parseArgs(String[] args) { Map<String, String> result = new HashMap<String, String>(); Set<String> allowedKeys = new HashSet<String>( Arrays.asList(PARAM_ADDITIONAL, PARAM_SCRIPT, PARAM_REGISTRY_PORT)); for (String arg : args) { if (arg.startsWith("-")) { int eqPos = arg.indexOf("="); if (eqPos >= 0) { String key = arg.substring(1, eqPos); if (!allowedKeys.contains(key)) { wrongUsage(); } String val = arg.substring(eqPos + 1); result.put(key, val); } else { wrongUsage(); } } else { wrongUsage(); } } return result; } }
public class class_name { public Map<String, String> parseArgs(String[] args) { Map<String, String> result = new HashMap<String, String>(); Set<String> allowedKeys = new HashSet<String>( Arrays.asList(PARAM_ADDITIONAL, PARAM_SCRIPT, PARAM_REGISTRY_PORT)); for (String arg : args) { if (arg.startsWith("-")) { int eqPos = arg.indexOf("="); if (eqPos >= 0) { String key = arg.substring(1, eqPos); if (!allowedKeys.contains(key)) { wrongUsage(); // depends on control dependency: [if], data = [none] } String val = arg.substring(eqPos + 1); result.put(key, val); // depends on control dependency: [if], data = [none] } else { wrongUsage(); // depends on control dependency: [if], data = [none] } } else { wrongUsage(); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { protected void routeTo(String msg, LogRecord logRecord, String logHandlerId) { LogHandler logHandler = logHandlerServices.get(logHandlerId); if (logHandler != null) { logHandler.publish(msg, logRecord); } } }
public class class_name { protected void routeTo(String msg, LogRecord logRecord, String logHandlerId) { LogHandler logHandler = logHandlerServices.get(logHandlerId); if (logHandler != null) { logHandler.publish(msg, logRecord); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void updatePluginConfiguration(PluginConfiguration value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; Element root = updateElement(counter, element, xmlTag, shouldExist); if (shouldExist) { Counter innerCount = new Counter(counter.getDepth() + 1); updatePluginManagement(value.getPluginManagement(), "pluginManagement", innerCount, root); iteratePlugin(innerCount, root, value.getPlugins(), "plugins", "plugin"); } } }
public class class_name { protected void updatePluginConfiguration(PluginConfiguration value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; Element root = updateElement(counter, element, xmlTag, shouldExist); if (shouldExist) { Counter innerCount = new Counter(counter.getDepth() + 1); updatePluginManagement(value.getPluginManagement(), "pluginManagement", innerCount, root); // depends on control dependency: [if], data = [none] iteratePlugin(innerCount, root, value.getPlugins(), "plugins", "plugin"); // depends on control dependency: [if], data = [none] } } }
public class class_name { public java.util.List<ClusterSubnetGroup> getClusterSubnetGroups() { if (clusterSubnetGroups == null) { clusterSubnetGroups = new com.amazonaws.internal.SdkInternalList<ClusterSubnetGroup>(); } return clusterSubnetGroups; } }
public class class_name { public java.util.List<ClusterSubnetGroup> getClusterSubnetGroups() { if (clusterSubnetGroups == null) { clusterSubnetGroups = new com.amazonaws.internal.SdkInternalList<ClusterSubnetGroup>(); // depends on control dependency: [if], data = [none] } return clusterSubnetGroups; } }
public class class_name { protected <T, K extends Serializable> Query<T> _buildQuery( final DAO<T, K> dao, final Class<T> type, final QueryParams params ) { Query<T> query = null; try { query = dao.createQuery(); QueryBuilder builder = _getQueryBuilderFactory().newBuilder( type ); query = builder.build( query, params ); } catch (RepositoryConfigurationException ex) { throw ex; } catch (QueryException ex) { throw ex; } catch (Exception ex) { throw new QueryException( ex ); } return query; } }
public class class_name { protected <T, K extends Serializable> Query<T> _buildQuery( final DAO<T, K> dao, final Class<T> type, final QueryParams params ) { Query<T> query = null; try { query = dao.createQuery(); // depends on control dependency: [try], data = [none] QueryBuilder builder = _getQueryBuilderFactory().newBuilder( type ); query = builder.build( query, params ); // depends on control dependency: [try], data = [none] } catch (RepositoryConfigurationException ex) { throw ex; } catch (QueryException ex) { // depends on control dependency: [catch], data = [none] throw ex; } catch (Exception ex) { // depends on control dependency: [catch], data = [none] throw new QueryException( ex ); } // depends on control dependency: [catch], data = [none] return query; } }
public class class_name { static boolean isDirectory(final File file) { try { Boolean exists = getInstance().doPrivileged( new PrivilegedAction<Boolean>() { public Boolean run() { return Boolean.valueOf(file.isDirectory()); } } ); return exists.booleanValue(); } catch (SecurityException se) { // TODO: Add logging here but be careful since this code is used in logging logic itself // and may result in an indefinite loop. return false; } } }
public class class_name { static boolean isDirectory(final File file) { try { Boolean exists = getInstance().doPrivileged( new PrivilegedAction<Boolean>() { public Boolean run() { return Boolean.valueOf(file.isDirectory()); } } ); return exists.booleanValue(); // depends on control dependency: [try], data = [none] } catch (SecurityException se) { // TODO: Add logging here but be careful since this code is used in logging logic itself // and may result in an indefinite loop. return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void add(K key, V value) { if (treatCollectionsAsImmutable) { Collection<V> newC = cf.newCollection(); Collection<V> c = map.get(key); if (c != null) { newC.addAll(c); } newC.add(value); map.put(key, newC); // replacing the old collection } else { Collection<V> c = map.get(key); if (c == null) { c = cf.newCollection(); map.put(key, c); } c.add(value); // modifying the old collection } } }
public class class_name { public void add(K key, V value) { if (treatCollectionsAsImmutable) { Collection<V> newC = cf.newCollection(); Collection<V> c = map.get(key); if (c != null) { newC.addAll(c); // depends on control dependency: [if], data = [(c] } newC.add(value); // depends on control dependency: [if], data = [none] map.put(key, newC); // replacing the old collection // depends on control dependency: [if], data = [none] } else { Collection<V> c = map.get(key); if (c == null) { c = cf.newCollection(); // depends on control dependency: [if], data = [none] map.put(key, c); // depends on control dependency: [if], data = [none] } c.add(value); // modifying the old collection // depends on control dependency: [if], data = [none] } } }
public class class_name { private long interpolateTimeSinceUpdate(TrackPositionUpdate update, long currentTimestamp) { if (!update.playing) { return update.milliseconds; } long elapsedMillis = (currentTimestamp - update.timestamp) / 1000000; long moved = Math.round(update.pitch * elapsedMillis); if (update.reverse) { return update.milliseconds - moved; } return update.milliseconds + moved; } }
public class class_name { private long interpolateTimeSinceUpdate(TrackPositionUpdate update, long currentTimestamp) { if (!update.playing) { return update.milliseconds; // depends on control dependency: [if], data = [none] } long elapsedMillis = (currentTimestamp - update.timestamp) / 1000000; long moved = Math.round(update.pitch * elapsedMillis); if (update.reverse) { return update.milliseconds - moved; // depends on control dependency: [if], data = [none] } return update.milliseconds + moved; } }
public class class_name { protected void updateRepositoryPolicy(RepositoryPolicy value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; Element root = updateElement(counter, element, xmlTag, shouldExist); if (shouldExist) { Counter innerCount = new Counter(counter.getDepth() + 1); findAndReplaceSimpleElement(innerCount, root, "enabled", (value.isEnabled() == true) ? null : String.valueOf(value.isEnabled()), "true"); findAndReplaceSimpleElement(innerCount, root, "updatePolicy", value.getUpdatePolicy(), null); findAndReplaceSimpleElement(innerCount, root, "checksumPolicy", value.getChecksumPolicy(), null); } } }
public class class_name { protected void updateRepositoryPolicy(RepositoryPolicy value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; Element root = updateElement(counter, element, xmlTag, shouldExist); if (shouldExist) { Counter innerCount = new Counter(counter.getDepth() + 1); findAndReplaceSimpleElement(innerCount, root, "enabled", (value.isEnabled() == true) ? null : String.valueOf(value.isEnabled()), "true"); // depends on control dependency: [if], data = [none] findAndReplaceSimpleElement(innerCount, root, "updatePolicy", value.getUpdatePolicy(), null); // depends on control dependency: [if], data = [none] findAndReplaceSimpleElement(innerCount, root, "checksumPolicy", value.getChecksumPolicy(), null); // depends on control dependency: [if], data = [none] } } }
public class class_name { @SafeVarargs public static <T> Map<T, T> createMap(T... _args) { Map<T, T> map = new HashMap<>(); if (_args != null) { if (_args.length % 2 != 0) { throw new IllegalArgumentException("Even number of parameters required to create map: " + Arrays.toString(_args)); } for (int i = 0; i < _args.length;) { map.put(_args[i], _args[i + 1]); i += 2; } } return map; } }
public class class_name { @SafeVarargs public static <T> Map<T, T> createMap(T... _args) { Map<T, T> map = new HashMap<>(); if (_args != null) { if (_args.length % 2 != 0) { throw new IllegalArgumentException("Even number of parameters required to create map: " + Arrays.toString(_args)); } for (int i = 0; i < _args.length;) { map.put(_args[i], _args[i + 1]); // depends on control dependency: [for], data = [i] i += 2; // depends on control dependency: [for], data = [i] } } return map; } }
public class class_name { public static List<String> reverse(final String[] array) { ArgUtils.notNull(array, "array"); if(array.length == 0) { return new ArrayList<String>(); } final List<String> list = Arrays.asList(array); Collections.sort(list, new Comparator<String>() { @Override public int compare(final String str1, final String str2) { int len1 = str1.length(); int len2 = str2.length(); if(len1 != len2) { // 逆順 return Integer.compare(len1, len2) * -1; } else { // 逆順 return str1.compareTo(str2) * 1; } } }); return list; } }
public class class_name { public static List<String> reverse(final String[] array) { ArgUtils.notNull(array, "array"); if(array.length == 0) { return new ArrayList<String>(); // depends on control dependency: [if], data = [none] } final List<String> list = Arrays.asList(array); Collections.sort(list, new Comparator<String>() { @Override public int compare(final String str1, final String str2) { int len1 = str1.length(); int len2 = str2.length(); if(len1 != len2) { // 逆順 return Integer.compare(len1, len2) * -1; // depends on control dependency: [if], data = [(len1] } else { // 逆順 return str1.compareTo(str2) * 1; // depends on control dependency: [if], data = [none] } } }); return list; } }
public class class_name { private boolean matchAndConvertArgs( List<Object> convertedArgumentList, BaseAccess methodAccess, Class[] parameterTypes, int index, boolean[] flag, boolean loose) { Object value = null; try { Class parameterClass; Object item; parameterClass = parameterTypes[index]; item = convertedArgumentList.get( index ); final TypeType parameterType = TypeType.getType(parameterClass); if ( item instanceof ValueContainer) { item = ( ( ValueContainer ) item ).toValue(); convertedArgumentList.set( index, item ); } if (item == null) { return true; } switch (parameterType) { case INT: case SHORT: case BYTE: case BOOLEAN: case CHAR: case FLOAT: case DOUBLE: case LONG: if (item == null) { return false; } case INTEGER_WRAPPER: case BYTE_WRAPPER: case SHORT_WRAPPER: case BOOLEAN_WRAPPER: case CHAR_WRAPPER: case FLOAT_WRAPPER: case DOUBLE_WRAPPER: case CHAR_SEQUENCE: case NUMBER: case LONG_WRAPPER: if (!loose ) { if (item instanceof Number) { value = Conversions.coerceWithFlag(parameterType, parameterClass, flag, item ); convertedArgumentList.set( index, value ); return flag[0]; } else { return false; } } else { value = Conversions.coerceWithFlag(parameterType, parameterClass, flag, item ); convertedArgumentList.set( index, value ); return flag[0]; } case ENUM: if (item instanceof Enum) { return true; } if (item instanceof CharSequence) { value = toEnum(parameterClass, item.toString()); convertedArgumentList.set( index, value ); return value!=null; } else if (item instanceof Number){ value = toEnum(parameterClass, ((Number)item).intValue()); convertedArgumentList.set( index, value ); return value!=null; } else { return false; } case CLASS: if (item instanceof Class) { return true; } value = Conversions.coerceWithFlag(parameterType, parameterClass, flag, item ); convertedArgumentList.set( index, value ); return flag[0]; case STRING: if (item instanceof String) { return true; } if (item instanceof CharSequence) { value = item.toString(); convertedArgumentList.set( index, value ); return true; } else if (loose) { value = item.toString(); convertedArgumentList.set( index, value ); return true; } else { return false; } case MAP: case VALUE_MAP: if (item instanceof Map) { Map itemMap = (Map)item; /* This code creates a map based on the parameterized types of the constructor arg. * This does ninja level generics manipulations and needs to be captured in some * reusable way. * */ Type type = methodAccess.getGenericParameterTypes()[index]; if ( type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Class<?> keyType = (Class<?>) pType.getActualTypeArguments()[0]; Class<?> valueType = (Class<?>) pType.getActualTypeArguments()[1]; Map newMap = Conversions.createMap(parameterClass, itemMap.size()); /* Iterate through the map items and convert the keys/values to match the parameterized constructor parameter args. */ for (Object o : itemMap.entrySet()) { Map.Entry entry = (Map.Entry) o; Object key = entry.getKey(); value = entry.getValue(); key = ValueContainer.toObject(key); value = ValueContainer.toObject(value); /* Here is the actual conversion from a list or a map of some object. This can be captured in helper method the duplication is obvious. */ if (value instanceof List) { value = fromList((List) value, valueType); } else if (value instanceof Map) { value = fromMap((Map) value, valueType); } else { value = coerce(valueType, value); } if (key instanceof List) { key = fromList((List) key, keyType); } else if (value instanceof Map) { key = fromMap((Map) key, keyType); } else { key = coerce(keyType, key); } newMap.put(key, value); } convertedArgumentList.set(index, newMap); return true; } } break; case INSTANCE: if ( parameterClass.isInstance( item ) ) { return true; } if (item instanceof Map) { item = fromMap( ( Map<String, Object> ) item, parameterClass ); convertedArgumentList.set( index, item ); return true; } else if ( item instanceof List ) { List<Object> listItem = null; listItem = ( List<Object> ) item; value = fromList(listItem, parameterClass ); convertedArgumentList.set( index, value ); return true; } else { convertedArgumentList.set( index, coerce( parameterClass, item ) ); return true; } //break; case INTERFACE: case ABSTRACT: if ( parameterClass.isInstance( item ) ) { return true; } if (item instanceof Map) { /** Handle conversion of user define interfaces. */ String className = (String) ((Map) item).get("class"); if (className != null) { item = fromMap( (Map<String, Object>) item, Reflection.loadClass(className)); convertedArgumentList.set(index, item); return true; } else { return false; } } break; case ARRAY: case ARRAY_INT: case ARRAY_BYTE: case ARRAY_SHORT: case ARRAY_FLOAT: case ARRAY_DOUBLE: case ARRAY_LONG: case ARRAY_STRING: case ARRAY_OBJECT: item = Conversions.toList(item); case SET: case COLLECTION: case LIST: if (item instanceof List ) { List<Object> itemList = ( List<Object> ) item; /* Items have stuff in it, the item is a list of lists. * This is like we did earlier with the map. * Here is some more ninja generics Java programming that needs to be captured in one place. * */ if ( itemList.size() > 0 && (itemList.get( 0 ) instanceof List || itemList.get(0) instanceof ValueContainer) ) { /** Grab the generic type of the list. */ Type type = methodAccess.getGenericParameterTypes()[index]; /* Try to pull the generic type information out so you can create a strongly typed list to inject. */ if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type; Class<?> componentType; if (! (pType.getActualTypeArguments()[0] instanceof Class)) { componentType = Object.class; } else { componentType = (Class<?>) pType.getActualTypeArguments()[0]; } Collection newList = Conversions.createCollection( parameterClass, itemList.size() ); for ( Object o : itemList ) { if ( o instanceof ValueContainer ) { o = ( ( ValueContainer ) o ).toValue(); } if (componentType==Object.class) { newList.add(o); } else { List fromList = ( List ) o; o = fromList( fromList, componentType ); newList.add( o ); } } convertedArgumentList.set( index, newList ); return true; } } else { /* Just a list not a list of lists so see if it has generics and pull out the * type information and created a strong typed list. This looks a bit familiar. * There is a big opportunity for some reuse here. */ Type type = methodAccess.getGenericParameterTypes()[index]; if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type; Class<?> componentType = pType.getActualTypeArguments()[0] instanceof Class ? (Class<?>) pType.getActualTypeArguments()[0] : Object.class; Collection newList = Conversions.createCollection( parameterClass, itemList.size() ); for ( Object o : itemList ) { if ( o instanceof ValueContainer ) { o = ( ( ValueContainer ) o ).toValue(); } if (o instanceof List) { if (componentType != Object.class) { List fromList = ( List ) o; o = fromList(fromList, componentType); } newList.add( o ); } else if (o instanceof Map) { Map fromMap = ( Map ) o; o = fromMap( fromMap, componentType ); newList.add( o ); } else { newList.add( Conversions.coerce(componentType, o)); } } convertedArgumentList.set( index, newList ); return true; } } } return false; default: final TypeType itemType = TypeType.getInstanceType(item); switch (itemType) { case LIST: convertedArgumentList.set(index, fromList((List<Object>) item, parameterClass)); return true; case MAP: case VALUE_MAP: convertedArgumentList.set(index, fromMap( (Map<String, Object>) item, parameterClass)); return true; case NUMBER: case BOOLEAN: case INT: case SHORT: case BYTE: case FLOAT: case DOUBLE: case LONG: case DOUBLE_WRAPPER: case FLOAT_WRAPPER: case INTEGER_WRAPPER: case SHORT_WRAPPER: case BOOLEAN_WRAPPER: case BYTE_WRAPPER: case LONG_WRAPPER: case CLASS: case VALUE: value = Conversions.coerceWithFlag( parameterClass, flag, item ); if (flag[0] == false) { return false; } convertedArgumentList.set( index, value ); return true; case CHAR_SEQUENCE: case STRING: value = Conversions.coerceWithFlag( parameterClass, flag, item ); if (flag[0] == false) { return false; } convertedArgumentList.set( index, value ); return true; } } if ( parameterClass.isInstance( item ) ) { return true; } } catch (Exception ex) { Boon.error(ex, "PROBLEM WITH oldMatchAndConvertArgs", "fieldsAccessor", fieldsAccessor, "list", convertedArgumentList, "constructor", methodAccess, "parameters", parameterTypes, "index", index); return false; } return false; } }
public class class_name { private boolean matchAndConvertArgs( List<Object> convertedArgumentList, BaseAccess methodAccess, Class[] parameterTypes, int index, boolean[] flag, boolean loose) { Object value = null; try { Class parameterClass; Object item; parameterClass = parameterTypes[index]; // depends on control dependency: [try], data = [none] item = convertedArgumentList.get( index ); // depends on control dependency: [try], data = [none] final TypeType parameterType = TypeType.getType(parameterClass); if ( item instanceof ValueContainer) { item = ( ( ValueContainer ) item ).toValue(); // depends on control dependency: [if], data = [none] convertedArgumentList.set( index, item ); // depends on control dependency: [if], data = [none] } if (item == null) { return true; // depends on control dependency: [if], data = [none] } switch (parameterType) { case INT: case SHORT: case BYTE: case BOOLEAN: case CHAR: case FLOAT: case DOUBLE: case LONG: if (item == null) { return false; // depends on control dependency: [if], data = [none] } case INTEGER_WRAPPER: case BYTE_WRAPPER: case SHORT_WRAPPER: case BOOLEAN_WRAPPER: case CHAR_WRAPPER: case FLOAT_WRAPPER: case DOUBLE_WRAPPER: case CHAR_SEQUENCE: case NUMBER: case LONG_WRAPPER: if (!loose ) { if (item instanceof Number) { value = Conversions.coerceWithFlag(parameterType, parameterClass, flag, item ); // depends on control dependency: [if], data = [none] convertedArgumentList.set( index, value ); // depends on control dependency: [if], data = [none] return flag[0]; // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } } else { value = Conversions.coerceWithFlag(parameterType, parameterClass, flag, item ); // depends on control dependency: [if], data = [none] convertedArgumentList.set( index, value ); // depends on control dependency: [if], data = [none] return flag[0]; // depends on control dependency: [if], data = [none] } case ENUM: if (item instanceof Enum) { return true; // depends on control dependency: [if], data = [none] } if (item instanceof CharSequence) { value = toEnum(parameterClass, item.toString()); // depends on control dependency: [if], data = [none] convertedArgumentList.set( index, value ); // depends on control dependency: [if], data = [none] return value!=null; // depends on control dependency: [if], data = [none] } else if (item instanceof Number){ value = toEnum(parameterClass, ((Number)item).intValue()); // depends on control dependency: [if], data = [none] convertedArgumentList.set( index, value ); // depends on control dependency: [if], data = [none] return value!=null; // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } case CLASS: if (item instanceof Class) { return true; // depends on control dependency: [if], data = [none] } value = Conversions.coerceWithFlag(parameterType, parameterClass, flag, item ); convertedArgumentList.set( index, value ); return flag[0]; case STRING: if (item instanceof String) { return true; // depends on control dependency: [if], data = [none] } if (item instanceof CharSequence) { value = item.toString(); // depends on control dependency: [if], data = [none] convertedArgumentList.set( index, value ); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } else if (loose) { value = item.toString(); // depends on control dependency: [if], data = [none] convertedArgumentList.set( index, value ); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } case MAP: case VALUE_MAP: if (item instanceof Map) { Map itemMap = (Map)item; /* This code creates a map based on the parameterized types of the constructor arg. * This does ninja level generics manipulations and needs to be captured in some * reusable way. * */ Type type = methodAccess.getGenericParameterTypes()[index]; if ( type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Class<?> keyType = (Class<?>) pType.getActualTypeArguments()[0]; Class<?> valueType = (Class<?>) pType.getActualTypeArguments()[1]; Map newMap = Conversions.createMap(parameterClass, itemMap.size()); /* Iterate through the map items and convert the keys/values to match the parameterized constructor parameter args. */ for (Object o : itemMap.entrySet()) { Map.Entry entry = (Map.Entry) o; Object key = entry.getKey(); value = entry.getValue(); // depends on control dependency: [for], data = [none] key = ValueContainer.toObject(key); // depends on control dependency: [for], data = [o] value = ValueContainer.toObject(value); // depends on control dependency: [for], data = [o] /* Here is the actual conversion from a list or a map of some object. This can be captured in helper method the duplication is obvious. */ if (value instanceof List) { value = fromList((List) value, valueType); // depends on control dependency: [if], data = [none] } else if (value instanceof Map) { value = fromMap((Map) value, valueType); // depends on control dependency: [if], data = [none] } else { value = coerce(valueType, value); // depends on control dependency: [if], data = [none] } if (key instanceof List) { key = fromList((List) key, keyType); // depends on control dependency: [if], data = [none] } else if (value instanceof Map) { key = fromMap((Map) key, keyType); // depends on control dependency: [if], data = [none] } else { key = coerce(keyType, key); // depends on control dependency: [if], data = [none] } newMap.put(key, value); // depends on control dependency: [for], data = [none] } convertedArgumentList.set(index, newMap); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } } break; case INSTANCE: if ( parameterClass.isInstance( item ) ) { return true; // depends on control dependency: [if], data = [none] } if (item instanceof Map) { item = fromMap( ( Map<String, Object> ) item, parameterClass ); // depends on control dependency: [if], data = [none] convertedArgumentList.set( index, item ); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } else if ( item instanceof List ) { List<Object> listItem = null; listItem = ( List<Object> ) item; // depends on control dependency: [if], data = [none] value = fromList(listItem, parameterClass ); // depends on control dependency: [if], data = [none] convertedArgumentList.set( index, value ); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } else { convertedArgumentList.set( index, coerce( parameterClass, item ) ); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } //break; case INTERFACE: case ABSTRACT: if ( parameterClass.isInstance( item ) ) { return true; // depends on control dependency: [if], data = [none] } if (item instanceof Map) { /** Handle conversion of user define interfaces. */ String className = (String) ((Map) item).get("class"); if (className != null) { item = fromMap( (Map<String, Object>) item, Reflection.loadClass(className)); // depends on control dependency: [if], data = [(className] convertedArgumentList.set(index, item); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } } break; case ARRAY: case ARRAY_INT: case ARRAY_BYTE: case ARRAY_SHORT: case ARRAY_FLOAT: case ARRAY_DOUBLE: case ARRAY_LONG: case ARRAY_STRING: case ARRAY_OBJECT: item = Conversions.toList(item); case SET: case COLLECTION: case LIST: if (item instanceof List ) { List<Object> itemList = ( List<Object> ) item; /* Items have stuff in it, the item is a list of lists. * This is like we did earlier with the map. * Here is some more ninja generics Java programming that needs to be captured in one place. * */ if ( itemList.size() > 0 && (itemList.get( 0 ) instanceof List || itemList.get(0) instanceof ValueContainer) ) { /** Grab the generic type of the list. */ Type type = methodAccess.getGenericParameterTypes()[index]; /* Try to pull the generic type information out so you can create a strongly typed list to inject. */ if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type; Class<?> componentType; if (! (pType.getActualTypeArguments()[0] instanceof Class)) { componentType = Object.class; // depends on control dependency: [if], data = [none] } else { componentType = (Class<?>) pType.getActualTypeArguments()[0]; // depends on control dependency: [if], data = [none] } Collection newList = Conversions.createCollection( parameterClass, itemList.size() ); for ( Object o : itemList ) { if ( o instanceof ValueContainer ) { o = ( ( ValueContainer ) o ).toValue(); // depends on control dependency: [if], data = [none] } if (componentType==Object.class) { newList.add(o); // depends on control dependency: [if], data = [none] } else { List fromList = ( List ) o; o = fromList( fromList, componentType ); // depends on control dependency: [if], data = [none] newList.add( o ); // depends on control dependency: [if], data = [none] } } convertedArgumentList.set( index, newList ); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } } else { /* Just a list not a list of lists so see if it has generics and pull out the * type information and created a strong typed list. This looks a bit familiar. * There is a big opportunity for some reuse here. */ Type type = methodAccess.getGenericParameterTypes()[index]; if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type; Class<?> componentType = pType.getActualTypeArguments()[0] instanceof Class ? (Class<?>) pType.getActualTypeArguments()[0] : Object.class; // depends on control dependency: [if], data = [none] Collection newList = Conversions.createCollection( parameterClass, itemList.size() ); for ( Object o : itemList ) { if ( o instanceof ValueContainer ) { o = ( ( ValueContainer ) o ).toValue(); // depends on control dependency: [if], data = [none] } if (o instanceof List) { if (componentType != Object.class) { List fromList = ( List ) o; o = fromList(fromList, componentType); // depends on control dependency: [if], data = [none] } newList.add( o ); // depends on control dependency: [if], data = [none] } else if (o instanceof Map) { Map fromMap = ( Map ) o; o = fromMap( fromMap, componentType ); // depends on control dependency: [if], data = [none] newList.add( o ); // depends on control dependency: [if], data = [none] } else { newList.add( Conversions.coerce(componentType, o)); // depends on control dependency: [if], data = [none] } } convertedArgumentList.set( index, newList ); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } } } return false; default: final TypeType itemType = TypeType.getInstanceType(item); switch (itemType) { case LIST: convertedArgumentList.set(index, fromList((List<Object>) item, parameterClass)); return true; case MAP: case VALUE_MAP: convertedArgumentList.set(index, fromMap( (Map<String, Object>) item, parameterClass)); return true; case NUMBER: case BOOLEAN: case INT: case SHORT: case BYTE: case FLOAT: case DOUBLE: case LONG: case DOUBLE_WRAPPER: case FLOAT_WRAPPER: case INTEGER_WRAPPER: case SHORT_WRAPPER: case BOOLEAN_WRAPPER: case BYTE_WRAPPER: case LONG_WRAPPER: case CLASS: case VALUE: value = Conversions.coerceWithFlag( parameterClass, flag, item ); if (flag[0] == false) { return false; // depends on control dependency: [if], data = [none] } convertedArgumentList.set( index, value ); return true; case CHAR_SEQUENCE: case STRING: value = Conversions.coerceWithFlag( parameterClass, flag, item ); if (flag[0] == false) { return false; // depends on control dependency: [if], data = [none] } convertedArgumentList.set( index, value ); return true; } } if ( parameterClass.isInstance( item ) ) { return true; // depends on control dependency: [if], data = [none] } } catch (Exception ex) { Boon.error(ex, "PROBLEM WITH oldMatchAndConvertArgs", "fieldsAccessor", fieldsAccessor, "list", convertedArgumentList, "constructor", methodAccess, "parameters", parameterTypes, "index", index); return false; } // depends on control dependency: [catch], data = [none] return false; } }
public class class_name { private void updateBeanValueForRenderedRows() { WTableRowRenderer rowRenderer = (WTableRowRenderer) repeater.getRepeatedComponent(); TableModel model = getTableModel(); int index = 0; List<RowIdWrapper> wrappers = repeater.getBeanList(); int columnCount = getColumnCount(); for (RowIdWrapper wrapper : wrappers) { UIContext rowContext = repeater.getRowContext(wrapper, index++); List<Integer> rowIndex = wrapper.getRowIndex(); Class<? extends WComponent> expandRenderer = model.getRendererClass(rowIndex); if (expandRenderer == null) { // Process Columns for (int col = 0; col < columnCount; col++) { // Check if this cell is editable if (model.isCellEditable(rowIndex, col)) { updateBeanValueForColumnInRow(rowRenderer, rowContext, rowIndex, col, model); } } } else if (model.isCellEditable(rowIndex, -1)) { // Check if this expanded row is editable updateBeanValueForRowRenderer(rowRenderer, rowContext, expandRenderer); } } } }
public class class_name { private void updateBeanValueForRenderedRows() { WTableRowRenderer rowRenderer = (WTableRowRenderer) repeater.getRepeatedComponent(); TableModel model = getTableModel(); int index = 0; List<RowIdWrapper> wrappers = repeater.getBeanList(); int columnCount = getColumnCount(); for (RowIdWrapper wrapper : wrappers) { UIContext rowContext = repeater.getRowContext(wrapper, index++); List<Integer> rowIndex = wrapper.getRowIndex(); Class<? extends WComponent> expandRenderer = model.getRendererClass(rowIndex); if (expandRenderer == null) { // Process Columns for (int col = 0; col < columnCount; col++) { // Check if this cell is editable if (model.isCellEditable(rowIndex, col)) { updateBeanValueForColumnInRow(rowRenderer, rowContext, rowIndex, col, model); // depends on control dependency: [if], data = [none] } } } else if (model.isCellEditable(rowIndex, -1)) { // Check if this expanded row is editable updateBeanValueForRowRenderer(rowRenderer, rowContext, expandRenderer); // depends on control dependency: [if], data = [none] } } } }
public class class_name { private void checkTimer() { try { serviceThreadLock.lock(); if ( watchdogTimer == null ) { // if there is NOT an active timer if ( !issuedWatchdogWrappers.allValues().isEmpty() ) { // if there are active providers. LOGGER.debug( "starting up " + THREAD_NAME + ", " + watchdogFrequency + "ms check frequency" ); // create a new timer startWatchdogThread(); } } } finally { serviceThreadLock.unlock(); } } }
public class class_name { private void checkTimer() { try { serviceThreadLock.lock(); // depends on control dependency: [try], data = [none] if ( watchdogTimer == null ) { // if there is NOT an active timer if ( !issuedWatchdogWrappers.allValues().isEmpty() ) { // if there are active providers. LOGGER.debug( "starting up " + THREAD_NAME + ", " + watchdogFrequency + "ms check frequency" ); // depends on control dependency: [if], data = [none] // create a new timer startWatchdogThread(); // depends on control dependency: [if], data = [none] } } } finally { serviceThreadLock.unlock(); } } }
public class class_name { @Override protected void checkIfHeartbeatSkipped(String name, EventChannelStruct eventChannelStruct) { // Check if heartbeat have been skipped, can happen if // 1- the notifd is dead (if not ZMQ) // 2- the server is dead // 3- The network was down; // 4- The server has been restarted on another host. // long now = System.currentTimeMillis(); // boolean heartbeat_skipped = // ((now - eventChannelStruct.last_heartbeat) > KeepAliveThread.getHeartBeatPeriod()); if (KeepAliveThread.heartbeatHasBeenSkipped(eventChannelStruct) || eventChannelStruct.heartbeat_skipped || eventChannelStruct.notifd_failed) { eventChannelStruct.heartbeat_skipped = true; // Check notifd by trying to read an attribute of the event channel DevError dev_error = null; try { eventChannelStruct.eventChannel.MyFactory(); // Check if DS is now running on another host if (checkIfHostHasChanged(eventChannelStruct)) eventChannelStruct.notifd_failed = true; } catch (RuntimeException e1) { // MyFactory has failed dev_error = new DevError(); dev_error.severity = ErrSeverity.ERR; dev_error.origin = "NotifdEventConsumer.checkIfHeartbeatSkipped()"; dev_error.reason = "API_EventException"; dev_error.desc = "Connection failed with notify daemon"; // Try to add reason int pos = e1.toString().indexOf(":"); if (pos > 0) dev_error.desc += " (" + e1.toString().substring(0, pos) + ")"; eventChannelStruct.notifd_failed = true; // reset the event import info stored in DeviceProxy object // Until today, this feature is used only by Astor (import with external info). try { DeviceProxyFactory.get(name, eventChannelStruct.dbase.getUrl().getTangoHost()).set_evt_import_info(null); } catch (DevFailed e) { System.err.println("API received a DevFailed : " + e.errors[0].desc); } } // Force to reconnect if not using database if (!eventChannelStruct.use_db) eventChannelStruct.notifd_failed = true; // Check if has_notifd_closed_the_connection many times (nework blank) if (!eventChannelStruct.notifd_failed && eventChannelStruct.has_notifd_closed_the_connection >= 3) eventChannelStruct.notifd_failed = true; // If notifd_failed --> try to reconnect if (eventChannelStruct.notifd_failed) { eventChannelStruct.notifd_failed = !reconnect_to_channel(name); if (!eventChannelStruct.notifd_failed) reconnect_to_event(name); } Enumeration callback_structs = EventConsumer.getEventCallbackMap().elements(); while (callback_structs.hasMoreElements()) { EventCallBackStruct callback_struct = (EventCallBackStruct) callback_structs.nextElement(); if (callback_struct.channel_name.equals(name)) { // Push exception if (dev_error != null) pushReceivedException(eventChannelStruct, callback_struct, dev_error); else pushServerNotRespondingException(eventChannelStruct, callback_struct); // If reconnection done, try to re subscribe // and read attribute in synchronous mode if (!callback_struct.event_name.equals(eventNames[DATA_READY_EVENT])) if (!eventChannelStruct.notifd_failed) if (eventChannelStruct.consumer.reSubscribe(eventChannelStruct, callback_struct)) readAttributeAndPush(eventChannelStruct, callback_struct); } } }// end if heartbeat_skipped else eventChannelStruct.has_notifd_closed_the_connection = 0; } }
public class class_name { @Override protected void checkIfHeartbeatSkipped(String name, EventChannelStruct eventChannelStruct) { // Check if heartbeat have been skipped, can happen if // 1- the notifd is dead (if not ZMQ) // 2- the server is dead // 3- The network was down; // 4- The server has been restarted on another host. // long now = System.currentTimeMillis(); // boolean heartbeat_skipped = // ((now - eventChannelStruct.last_heartbeat) > KeepAliveThread.getHeartBeatPeriod()); if (KeepAliveThread.heartbeatHasBeenSkipped(eventChannelStruct) || eventChannelStruct.heartbeat_skipped || eventChannelStruct.notifd_failed) { eventChannelStruct.heartbeat_skipped = true; // depends on control dependency: [if], data = [none] // Check notifd by trying to read an attribute of the event channel DevError dev_error = null; try { eventChannelStruct.eventChannel.MyFactory(); // depends on control dependency: [try], data = [none] // Check if DS is now running on another host if (checkIfHostHasChanged(eventChannelStruct)) eventChannelStruct.notifd_failed = true; } catch (RuntimeException e1) { // MyFactory has failed dev_error = new DevError(); dev_error.severity = ErrSeverity.ERR; dev_error.origin = "NotifdEventConsumer.checkIfHeartbeatSkipped()"; dev_error.reason = "API_EventException"; dev_error.desc = "Connection failed with notify daemon"; // Try to add reason int pos = e1.toString().indexOf(":"); if (pos > 0) dev_error.desc += " (" + e1.toString().substring(0, pos) + ")"; eventChannelStruct.notifd_failed = true; // reset the event import info stored in DeviceProxy object // Until today, this feature is used only by Astor (import with external info). try { DeviceProxyFactory.get(name, eventChannelStruct.dbase.getUrl().getTangoHost()).set_evt_import_info(null); // depends on control dependency: [try], data = [none] } catch (DevFailed e) { System.err.println("API received a DevFailed : " + e.errors[0].desc); } // depends on control dependency: [catch], data = [none] } // depends on control dependency: [catch], data = [none] // Force to reconnect if not using database if (!eventChannelStruct.use_db) eventChannelStruct.notifd_failed = true; // Check if has_notifd_closed_the_connection many times (nework blank) if (!eventChannelStruct.notifd_failed && eventChannelStruct.has_notifd_closed_the_connection >= 3) eventChannelStruct.notifd_failed = true; // If notifd_failed --> try to reconnect if (eventChannelStruct.notifd_failed) { eventChannelStruct.notifd_failed = !reconnect_to_channel(name); // depends on control dependency: [if], data = [none] if (!eventChannelStruct.notifd_failed) reconnect_to_event(name); } Enumeration callback_structs = EventConsumer.getEventCallbackMap().elements(); while (callback_structs.hasMoreElements()) { EventCallBackStruct callback_struct = (EventCallBackStruct) callback_structs.nextElement(); if (callback_struct.channel_name.equals(name)) { // Push exception if (dev_error != null) pushReceivedException(eventChannelStruct, callback_struct, dev_error); else pushServerNotRespondingException(eventChannelStruct, callback_struct); // If reconnection done, try to re subscribe // and read attribute in synchronous mode if (!callback_struct.event_name.equals(eventNames[DATA_READY_EVENT])) if (!eventChannelStruct.notifd_failed) if (eventChannelStruct.consumer.reSubscribe(eventChannelStruct, callback_struct)) readAttributeAndPush(eventChannelStruct, callback_struct); } } }// end if heartbeat_skipped else eventChannelStruct.has_notifd_closed_the_connection = 0; } }