id
stringlengths 19
22
| content
stringlengths 187
14.2k
| max_stars_repo_path
stringlengths 15
210
|
|---|---|---|
satd-removal_data_1
|
TODO: make this a big red scary button
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mDisk == null) {
finish();
return;
}
setContentView(R.layout.storage_wizard_generic);
mFormatPrivate = getIntent().getBooleanExtra(EXTRA_FORMAT_PRIVATE, false);
if (mFormatPrivate) {
setHeaderText(R.string.storage_wizard_format_confirm_title);
setBodyText(R.string.storage_wizard_format_confirm_body,
mDisk.getDescription());
} else {
setHeaderText(R.string.storage_wizard_format_confirm_public_title);
setBodyText(R.string.storage_wizard_format_confirm_public_body,
mDisk.getDescription());
}
// TODO: make this a big red scary button
getNextButton().setText(R.string.storage_wizard_format_confirm_next);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mDisk == null) {
finish();
return;
}
setContentView(R.layout.storage_wizard_generic);
mFormatPrivate = getIntent().getBooleanExtra(EXTRA_FORMAT_PRIVATE, false);
setIllustrationInternal(mFormatPrivate);
if (mFormatPrivate) {
setHeaderText(R.string.storage_wizard_format_confirm_title);
setBodyText(R.string.storage_wizard_format_confirm_body,
mDisk.getDescription());
} else {
setHeaderText(R.string.storage_wizard_format_confirm_public_title);
setBodyText(R.string.storage_wizard_format_confirm_public_body,
mDisk.getDescription());
}
getNextButton().setText(R.string.storage_wizard_format_confirm_next);
getNextButton().setBackgroundTintList(getColorStateList(R.color.storage_wizard_button_red));
}
|
src/com/android/settings/deviceinfo/StorageWizardFormatConfirm.java
|
satd-removal_data_2
|
TODO: catch expectation failures and resignal correctly
public void invokeWithJavaArgs(Object[] args) throws Throwable {
IokeObject msg = ioke.newMessage("invoke");
Message invoke = (Message) IokeObject.data(msg);
// TODO: catch expectation failures and resignal correctly
List<Runtime.RescueInfo> pendingRescues = new ArrayList<Runtime.RescueInfo>();
IokeObject rr = IokeObject.as(((Message)IokeObject.data(ioke.mimic)).sendTo(ioke.mimic, ioke.ground, ioke.rescue), ioke.ground);
List<Object> conds = new ArrayList();
final IokeObject pendingCondition = IokeObject.as(IokeObject.getCellChain(ioke.condition,
ioke.message,
ioke.ground,
"Pending"), ioke.ground);
conds.add(pendingCondition);
pendingRescues.add(new Runtime.RescueInfo(rr, conds, pendingRescues, ioke.getBindIndex()));
ioke.registerRescues(pendingRescues);
try {
invoke.sendTo(msg, iokeStepDefObject, iokeStepDefObject, multilineArg(args));
} catch(ControlFlow.Rescue e) {
if(e.getRescue().token == pendingRescues) {
throw JRuby.cucumberPending("TODO");
// throw (Exception)(e.getCondition().getCell(ioke.message, ioke.ground, "rootException"));
} else {
throw e;
}
} finally {
ioke.unregisterRescues(pendingRescues);
}
}
public void invokeWithJavaArgs(Object[] args) throws Throwable {
IokeObject msg = ioke.newMessage("invoke");
Message invoke = (Message) IokeObject.data(msg);
List<Runtime.RescueInfo> pendingRescues = new ArrayList<Runtime.RescueInfo>();
IokeObject rr = IokeObject.as(((Message)IokeObject.data(ioke.mimic)).sendTo(ioke.mimic, ioke.ground, ioke.rescue), ioke.ground);
List<Object> conds = new ArrayList();
conds.add(lang.pendingCondition);
pendingRescues.add(new Runtime.RescueInfo(rr, conds, pendingRescues, ioke.getBindIndex()));
ioke.registerRescues(pendingRescues);
List<Runtime.RescueInfo> failureRescues = new ArrayList<Runtime.RescueInfo>();
IokeObject rr2 = IokeObject.as(((Message)IokeObject.data(ioke.mimic)).sendTo(ioke.mimic, ioke.ground, ioke.rescue), ioke.ground);
List<Object> failureConds = new ArrayList();
failureConds.add(lang.failedExpectationCondition);
failureRescues.add(new Runtime.RescueInfo(rr2, failureConds, failureRescues, ioke.getBindIndex()));
ioke.registerRescues(failureRescues);
try {
invoke.sendTo(msg, iokeStepDefObject, iokeStepDefObject, multilineArg(args));
} catch(ControlFlow.Rescue e) {
if(e.getRescue().token == pendingRescues) {
throw JRuby.cucumberPending("TODO");
} else if(e.getRescue().token == failureRescues) {
throwCucumberIokeException(((Message)IokeObject.data(ioke.reportMessage)).sendTo(ioke.reportMessage, ioke.ground, e.getCondition()).toString());
} else {
throw e;
}
} finally {
ioke.unregisterRescues(failureRescues);
ioke.unregisterRescues(pendingRescues);
}
}
|
cuke4duke/src/main/java/cuke4duke/internal/ik/IkStepDefinition.java
|
satd-removal_data_3
|
FIXME: this is broken and untested (it should set the mark instead of limit)
public void mark() {
// FIXME: this is broken and untested (it should set the mark instead of limit)
this.limit = position.duplicate();
}
public void mark() {
this.mark = position.duplicate();
}
|
codec/src/main/java/org/apache/mina/codec/IoBuffer.java
|
satd-removal_data_4
|
TODO support unicode!
private static StringBuilder ioListToStringBuilder(final OtpErlangObject o,
final StringBuilder sb0, final int maxLength) {
StringBuilder sb = sb0;
if (sb.length() >= maxLength) {
return sb;
}
if (o instanceof OtpErlangLong) {
final OtpErlangLong l = (OtpErlangLong) o;
try {
sb.append(l.charValue());
} catch (final OtpErlangRangeException e) {
}
} else if (o instanceof OtpErlangString) {
final OtpErlangString s = (OtpErlangString) o;
sb.append(s.stringValue());
} else if (o instanceof OtpErlangList) {
final OtpErlangList l = (OtpErlangList) o;
for (final OtpErlangObject i : l) {
if (sb.length() < maxLength) {
ioListToStringBuilder(i, sb, maxLength);
}
}
if (sb.length() < maxLength) {
ioListToStringBuilder(l.getLastTail(), sb, maxLength);
}
} else if (o instanceof OtpErlangBinary) {
final OtpErlangBinary b = (OtpErlangBinary) o;
// TODO support unicode!
final String s = new String(b.binaryValue(), Charsets.ISO_8859_1);
sb.append(s);
} else if (o != null) {
sb.append(o.toString());
}
if (sb.length() > maxLength) {
sb = new StringBuilder(sb.substring(0, maxLength));
sb.append("... <truncated>");
}
return sb;
}
private static StringBuilder ioListToStringBuilder(final OtpErlangObject o,
final StringBuilder sb0, final int maxLength) {
StringBuilder sb = sb0;
if (sb.length() >= maxLength) {
return sb;
}
if (o instanceof OtpErlangLong) {
final OtpErlangLong l = (OtpErlangLong) o;
try {
sb.append(l.charValue());
} catch (final OtpErlangRangeException e) {
}
} else if (o instanceof OtpErlangString) {
final OtpErlangString s = (OtpErlangString) o;
sb.append(s.stringValue());
} else if (o instanceof OtpErlangList) {
final OtpErlangList l = (OtpErlangList) o;
for (final OtpErlangObject i : l) {
if (sb.length() < maxLength) {
ioListToStringBuilder(i, sb, maxLength);
}
}
if (sb.length() < maxLength) {
ioListToStringBuilder(l.getLastTail(), sb, maxLength);
}
} else if (o instanceof OtpErlangBinary) {
final OtpErlangBinary b = (OtpErlangBinary) o;
String s = decode(b.binaryValue(), Charsets.UTF_8);
if (s == null) {
s = new String(b.binaryValue(), Charsets.ISO_8859_1);
}
sb.append(s);
} else if (o != null) {
sb.append(o.toString());
}
if (sb.length() > maxLength) {
sb = new StringBuilder(sb.substring(0, maxLength));
sb.append("... <truncated>");
}
return sb;
}
|
org.erlide.util/src/org/erlide/util/Util.java
|
satd-removal_data_5
|
todo: need a reciprocal stop
protected void internalNonBlockingStart() throws IOException
{
try
{
// copy
TezConfiguration workingConf = new TezConfiguration( currentConf );
prepareEnsureStagingDir( workingConf );
tezClient = TezClient.create( flowStep.getName(), workingConf, Collections.<String, LocalResource>emptyMap(), credentials );
tezClient.start(); // todo: need a reciprocal stop
dagClient = tezClient.submitDAG( dag );
flowStep.logInfo( "submitted tez dag: " + dagClient.getExecutionContext() );
// if( dagClient.getApplicationReport() != null && dagClient.getApplicationReport().getTrackingUrl() != null )
// flowStep.logInfo( "tracking url: " + dagClient.getApplicationReport().getTrackingUrl() );
}
catch( TezException exception )
{
throw new CascadingException( exception );
}
}
protected void internalNonBlockingStart() throws IOException
{
try
{
TezConfiguration workingConf = new TezConfiguration( currentConf );
if( !workingConf.getBoolean( YarnConfiguration.TIMELINE_SERVICE_ENABLED, YarnConfiguration.DEFAULT_TIMELINE_SERVICE_ENABLED ) )
flowStep.logWarn( "'" + YarnConfiguration.TIMELINE_SERVICE_ENABLED + "' is disabled, please enable to capture detailed metrics of completed flows, this may require starting the YARN timeline server daemon." );
// this could be problematic
flowStep.logInfo( "tez session mode enabled: " + workingConf.getBoolean( TezConfiguration.TEZ_AM_SESSION_MODE, TezConfiguration.TEZ_AM_SESSION_MODE_DEFAULT ) );
prepareEnsureStagingDir( workingConf );
tezClient = TezClient.create( flowStep.getName(), workingConf, false );
tezClient.start();
dagClient = tezClient.submitDAG( dag );
flowStep.logInfo( "submitted tez dag to app master: " + tezClient.getAppMasterApplicationId() );
}
catch( TezException exception )
{
throw new CascadingException( exception );
}
}
|
cascading-hadoop2-tez/src/main/java/cascading/flow/tez/planner/Hadoop2TezFlowStepJob.java
|
satd-removal_data_6
|
XXX: REMOVE THIS SYNCHRONIZED: once threading issues in AS7 WS are fixed
public void start() throws WebServicePublishException {
ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
//XXX: REMOVE THIS SYNCHRONIZED: once threading issues in AS7 WS are fixed
synchronized (BaseWebService.class) {
try {
_service = _domain.getServiceReference(_config.getServiceName());
PortName portName = _config.getPort();
javax.wsdl.Service wsdlService = WSDLUtil.getService(_config.getWsdl(), portName);
_wsdlPort = WSDLUtil.getPort(wsdlService, portName);
// Update the portName
portName.setServiceQName(wsdlService.getQName());
portName.setName(_wsdlPort.getName());
BaseWebService wsProvider = new BaseWebService();
wsProvider.setInvocationClassLoader(Thread.currentThread().getContextClassLoader());
// Hook the handler
wsProvider.setConsumer(this);
List<Source> metadata = new ArrayList<Source>();
StreamSource source = WSDLUtil.getStream(_config.getWsdl());
metadata.add(source);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(Endpoint.WSDL_SERVICE, portName.getServiceQName());
properties.put(Endpoint.WSDL_PORT, portName.getPortQName());
properties.put(WSDL_LOCATION, WSDLUtil.getURL(_config.getWsdl()).toExternalForm());
String path = "/" + portName.getServiceName();
if (_config.getContextPath() != null) {
path = "/" + _config.getContextPath() + "/" + portName.getServiceName();
}
String publishUrl = _scheme + "://" + _config.getSocketAddr().getHost() + ":" + _config.getSocketAddr().getPort() + path;
LOGGER.info("Publishing WebService at " + publishUrl);
// make sure we don't pollute the class loader used by the WS subsystem
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
_endpoint = Endpoint.create(wsProvider);
_endpoint.setMetadata(metadata);
_endpoint.setProperties(properties);
_endpoint.publish(publishUrl);
} catch (MalformedURLException e) {
throw new WebServicePublishException(e);
} catch (WSDLException e) {
throw new WebServicePublishException(e);
} finally {
Thread.currentThread().setContextClassLoader(origLoader);
}
}
}
public void start() throws WebServicePublishException {
ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
try {
_service = _domain.getServiceReference(_config.getServiceName());
PortName portName = _config.getPort();
javax.wsdl.Service wsdlService = WSDLUtil.getService(_config.getWsdl(), portName);
_wsdlPort = WSDLUtil.getPort(wsdlService, portName);
// Update the portName
portName.setServiceQName(wsdlService.getQName());
portName.setName(_wsdlPort.getName());
BaseWebService wsProvider = new BaseWebService();
wsProvider.setInvocationClassLoader(Thread.currentThread().getContextClassLoader());
// Hook the handler
wsProvider.setConsumer(this);
List<Source> metadata = new ArrayList<Source>();
StreamSource source = WSDLUtil.getStream(_config.getWsdl());
metadata.add(source);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(Endpoint.WSDL_SERVICE, portName.getServiceQName());
properties.put(Endpoint.WSDL_PORT, portName.getPortQName());
properties.put(WSDL_LOCATION, WSDLUtil.getURL(_config.getWsdl()).toExternalForm());
String path = "/" + portName.getServiceName();
if (_config.getContextPath() != null) {
path = "/" + _config.getContextPath() + "/" + portName.getServiceName();
}
String publishUrl = _scheme + "://" + _config.getSocketAddr().getHost() + ":" + _config.getSocketAddr().getPort() + path;
LOGGER.info("Publishing WebService at " + publishUrl);
// make sure we don't pollute the class loader used by the WS subsystem
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
_endpoint = Endpoint.create(wsProvider);
_endpoint.setMetadata(metadata);
_endpoint.setProperties(properties);
_endpoint.publish(publishUrl);
} catch (MalformedURLException e) {
throw new WebServicePublishException(e);
} catch (WSDLException e) {
throw new WebServicePublishException(e);
} finally {
Thread.currentThread().setContextClassLoader(origLoader);
}
}
|
soap/src/main/java/org/switchyard/component/soap/InboundHandler.java
|
satd-removal_data_7
|
TODO 428889 extract root feature seeds on this class loader side
@Test
public void testPublishingWithRootFeatures() {
File productDefinition = resourceFile("publishers/products/rootFeatures.product");
subject = initPublisher(createFeatureIU("org.eclipse.rcp", "4.4.0.v20140128"),
createFeatureIU("org.eclipse.e4.rcp", "1.0"), createFeatureIU("org.eclipse.help", "2.0.102.v20140128"),
createFeatureIU("org.eclipse.egit", "2.0"));
// TODO 428889 this information shall come from the IProductDescriptor
Set<String> rootFeatures = new HashSet<String>(asList("org.eclipse.help", "org.eclipse.egit"));
IInstallableUnit unit = getUnit(subject.publishProduct(productDefinition, rootFeatures, null, FLAVOR));
assertThat(unit.getRequirements(), hasItem(requirement("org.eclipse.rcp.feature.group", "4.4.0.v20140128")));
assertThat(unit.getRequirements(), hasItem(requirement("org.eclipse.e4.rcp.feature.group", "1.0")));
assertThat(unit.getRequirements(),
not(hasItem(requirement("org.eclipse.help.feature.group", "2.0.102.v20140128"))));
assertThat(unit.getRequirements(), not(hasItem(requirement("org.eclipse.egit.feature.group", "2.0"))));
// TODO 428889 extract root feature seeds on this class loader side
}
@Test
public void testPublishingWithRootFeatures() {
File productDefinition = resourceFile("publishers/products/rootFeatures.product");
subject = initPublisher(createFeatureIU("org.eclipse.rcp", "4.4.0.v20140128"),
createFeatureIU("org.eclipse.e4.rcp", "1.0"), createFeatureIU("org.eclipse.help", "2.0.102.v20140128"),
createFeatureIU("org.eclipse.egit", "2.0"));
List<DependencySeed> seeds = subject.publishProduct(productDefinition, null, FLAVOR);
IInstallableUnit productUnit = getUnique(productUnit(), unitsIn(seeds));
assertThat(productUnit.getRequirements(),
hasItem(requirement("org.eclipse.rcp.feature.group", "4.4.0.v20140128")));
assertThat(productUnit.getRequirements(), hasItem(requirement("org.eclipse.e4.rcp.feature.group", "1.0")));
assertThat(productUnit.getRequirements(),
not(hasItem(requirement("org.eclipse.help.feature.group", "2.0.102.v20140128"))));
assertThat(productUnit.getRequirements(), not(hasItem(requirement("org.eclipse.egit.feature.group", "2.0"))));
assertThat(seeds.get(1).getId(), is("org.eclipse.help"));
assertThat((IInstallableUnit) seeds.get(1).getInstallableUnit(),
is(unitWithId("org.eclipse.help.feature.group")));
assertThat(seeds.get(2).getId(), is("org.eclipse.egit"));
assertThat((IInstallableUnit) seeds.get(2).getInstallableUnit(),
is(unitWithId("org.eclipse.egit.feature.group")));
assertThat(seeds, hasSize(3));
}
|
tycho-bundles/org.eclipse.tycho.p2.tools.tests/src/test/java/org/eclipse/tycho/p2/tools/publisher/PublishProductToolTest.java
|
satd-removal_data_8
|
TODO Check for existence of the getter and skip it (+ warn) if it's already there.
@Override public void handle(AnnotationValues<Getter> annotation, JCAnnotation ast, JavacAST.Node annotationNode) {
//TODO Check for existence of the getter and skip it (+ warn) if it's already there.
if ( annotationNode.up().getKind() != Kind.FIELD ) {
annotationNode.addError("@Getter is only supported on a field.");
return;
}
Getter getter = annotation.getInstance();
JCClassDecl javacClassTree = (JCClassDecl) annotationNode.up().up().get();
int access = toJavacModifier(getter.value());
JCMethodDecl getterMethod = createGetter(access, annotationNode.up(), annotationNode.getTreeMaker());
javacClassTree.defs = javacClassTree.defs.append(getterMethod);
}
@Override public void handle(AnnotationValues<Getter> annotation, JCAnnotation ast, JavacAST.Node annotationNode) {
if ( annotationNode.up().getKind() != Kind.FIELD ) {
annotationNode.addError("@Getter is only supported on a field.");
return;
}
String methodName = toGetterName((JCVariableDecl) annotationNode.up().get());
if ( methodExists(methodName, annotationNode.up()) ) {
annotationNode.addWarning(
String.format("Not generating %s(): A method with that name already exists", methodName));
return;
}
Getter getter = annotation.getInstance();
JCClassDecl javacClassTree = (JCClassDecl) annotationNode.up().up().get();
int access = toJavacModifier(getter.value());
JCMethodDecl getterMethod = createGetter(access, annotationNode.up(), annotationNode.getTreeMaker());
javacClassTree.defs = javacClassTree.defs.append(getterMethod);
}
|
src/lombok/javac/handlers/HandleGetter.java
|
satd-removal_data_9
|
TODO: Web Hosting #118779
@Test
public void testListImagesDetail() throws Exception {
List<Image> response = connection.listImageDetails();
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
for (Image image : response) {
assertTrue(image.getId() >= 1);
assert null != image.getName() : image;
// TODO: Web Hosting #118779
// assert null != image.getCreated() : image;
// assert null != image.getUpdated() : image;
assert null != image.getStatus() : image;
}
}
@Test
public void testListImagesDetail() throws Exception {
List<Image> response = connection.listImageDetails();
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
for (Image image : response) {
assertTrue(image.getId() >= 1);
assert null != image.getName() : image;
// sometimes this is not present per: Web Hosting #118820
// assert null != image.getCreated() : image;
assert null != image.getUpdated() : image;
assert null != image.getStatus() : image;
}
}
|
rackspace/cloudservers/core/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersConnectionLiveTest.java
|
satd-removal_data_10
|
TODO record duration
@Override
public void callRecordComplete(ResourceEvent event) {
Qualifier q = event.getQualifier();
RecordCompleteEvent.Cause cause = RecordCompleteEvent.Cause.UNKNOWN;
String errorText = null;
if (q == SpeechDetectorConstants.INITIAL_TIMEOUT_EXPIRED) {
cause = RecordCompleteEvent.Cause.INI_TIMEOUT;
}
else if (q == ResourceEvent.STOPPED) {
if (callRecording.isNormalDisconnect()) {
cause = RecordCompleteEvent.Cause.DISCONNECT;
}
else {
cause = RecordCompleteEvent.Cause.CANCEL;
}
}
else if (q == ResourceEvent.RTC_TRIGGERED) {
cause = RecordCompleteEvent.Cause.CANCEL;
}
else if (q == ResourceEvent.NO_QUALIFIER) {
if (event.getError() != ResourceEvent.NO_ERROR) {
cause = RecordCompleteEvent.Cause.ERROR;
}
errorText = event.getError() + ": " + event.getErrorText();
}
// TODO record duration
final RecordCompleteEvent<T> recordCompleteEvent = new MohoRecordCompleteEvent<T>(_parent, cause,
_dialect.getCallRecordDuration(event), errorText, callRecording);
_parent.dispatch(recordCompleteEvent);
callRecording.done(recordCompleteEvent);
_futures.remove(callRecording);
}
@Override
public void callRecordComplete(ResourceEvent event) {
Qualifier q = event.getQualifier();
RecordCompleteEvent.Cause cause = RecordCompleteEvent.Cause.UNKNOWN;
String errorText = null;
if (q == SpeechDetectorConstants.INITIAL_TIMEOUT_EXPIRED) {
cause = RecordCompleteEvent.Cause.INI_TIMEOUT;
}
else if (q == ResourceEvent.STOPPED) {
if (callRecording.isNormalDisconnect()) {
cause = RecordCompleteEvent.Cause.DISCONNECT;
}
else {
cause = RecordCompleteEvent.Cause.CANCEL;
}
}
else if (q == ResourceEvent.RTC_TRIGGERED) {
cause = RecordCompleteEvent.Cause.CANCEL;
}
else if (q == ResourceEvent.NO_QUALIFIER) {
if (event.getError() != ResourceEvent.NO_ERROR) {
cause = RecordCompleteEvent.Cause.ERROR;
}
errorText = event.getError() + ": " + event.getErrorText();
}
final RecordCompleteEvent<T> recordCompleteEvent = new MohoRecordCompleteEvent<T>(_parent, cause,
_dialect.getCallRecordDuration(event), errorText, callRecording);
_parent.dispatch(recordCompleteEvent);
callRecording.done(recordCompleteEvent);
_futures.remove(callRecording);
if(callRecording.getMaxDurationTimerFuture() != null) {
callRecording.getMaxDurationTimerFuture().cancel(true);
((ApplicationContextImpl) _context).getScheduledEcutor().remove(callRecording.getMaxDurationTask());
((ApplicationContextImpl) _context).getScheduledEcutor().purge();
}
}
|
moho-impl/src/main/java/com/voxeo/moho/media/GenericMediaService.java
|
satd-removal_data_11
|
TODO: Is this where we should handle this?
public void generateTables(String schemaName, String tableName,
Connection conn, DatabaseMetaData meta)
throws SQLException {
fireGenerationEvent(_loc.get("generating-columns", schemaName,
tableName));
if (_log.isTraceEnabled())
_log.trace(_loc.get("gen-tables", schemaName, tableName));
Column[] cols = _dict.getColumns(meta, conn.getCatalog(), schemaName,
tableName, null, conn);
// when we want to get all the columns for all tables, we need to build
// a list of tables to verify because some databases (e.g., Postgres)
// will include indexes in the list of columns, and there is no way to
// distinguish the indexes from proper columns
Set tableNames = null;
if (tableName == null || "%".equals(tableName)) {
Table[] tables = _dict.getTables(meta, conn.getCatalog(),
schemaName, tableName, conn);
tableNames = new HashSet();
for (int i = 0; tables != null && i < tables.length; i++) {
if (cols == null)
tableNames.add(tables[i].getName());
else
tableNames.add(tables[i].getName().toUpperCase());
}
}
// if database can't handle null table name, recurse on each known name
if (cols == null && tableName == null) {
for (Iterator itr = tableNames.iterator(); itr.hasNext();)
generateTables(schemaName, (String) itr.next(), conn, meta);
return;
}
SchemaGroup group = getSchemaGroup();
Schema schema;
Table table;
String tableSchema;
for (int i = 0; cols != null && i < cols.length; i++) {
// TODO: Is this where we should handle this?
if (tableName == null || tableName.equals("%")) {
tableName = cols[i].getTableName();
}
if (schemaName == null) {
tableSchema = StringUtils.trimToNull(cols[i].getSchemaName());
}
else {
tableSchema = schemaName;
}
// ignore special tables
if (!_openjpaTables &&
(tableName.toUpperCase().startsWith("OPENJPA_")
|| tableName.toUpperCase().startsWith("JDO_"))) // legacy
continue;
if (_dict.isSystemTable(tableName, tableSchema, schemaName != null))
continue;
// ignore tables not in list, or not allowed by schemas property
if (tableNames != null
&& !tableNames.contains(tableName.toUpperCase()))
continue;
if (!isAllowedTable(tableSchema, tableName))
continue;
schema = group.getSchema(tableSchema);
if (schema == null)
schema = group.addSchema(tableSchema);
table = schema.getTable(tableName);
if (table == null) {
table = schema.addTable(tableName);
if (_log.isTraceEnabled())
_log.trace(_loc.get("col-table", table));
}
if (_log.isTraceEnabled())
_log.trace(_loc.get("gen-column", cols[i].getName(), table));
if (table.getColumn(cols[i].getName()) == null)
table.importColumn(cols[i]);
}
}
public void generateTables(String schemaName, String tableName,
Connection conn, DatabaseMetaData meta)
throws SQLException {
fireGenerationEvent(_loc.get("generating-columns", schemaName,
tableName));
if (_log.isTraceEnabled())
_log.trace(_loc.get("gen-tables", schemaName, tableName));
Column[] cols = _dict.getColumns(meta, conn.getCatalog(), schemaName,
tableName, null, conn);
// when we want to get all the columns for all tables, we need to build
// a list of tables to verify because some databases (e.g., Postgres)
// will include indexes in the list of columns, and there is no way to
// distinguish the indexes from proper columns
Set tableNames = null;
if (tableName == null || "%".equals(tableName)) {
Table[] tables = _dict.getTables(meta, conn.getCatalog(),
schemaName, tableName, conn);
tableNames = new HashSet();
for (int i = 0; tables != null && i < tables.length; i++) {
if (cols == null)
tableNames.add(tables[i].getName());
else
tableNames.add(tables[i].getName().toUpperCase());
}
}
// if database can't handle null table name, recurse on each known name
if (cols == null && tableName == null) {
for (Iterator itr = tableNames.iterator(); itr.hasNext();)
generateTables(schemaName, (String) itr.next(), conn, meta);
return;
}
SchemaGroup group = getSchemaGroup();
Schema schema;
Table table;
String tableSchema;
for (int i = 0; cols != null && i < cols.length; i++) {
if (tableName == null || tableName.equals("%")) {
tableName = cols[i].getTableName();
}
if (schemaName == null) {
tableSchema = StringUtils.trimToNull(cols[i].getSchemaName());
}
else {
tableSchema = schemaName;
}
// ignore special tables
if (!_openjpaTables &&
(tableName.toUpperCase().startsWith("OPENJPA_")
|| tableName.toUpperCase().startsWith("JDO_"))) // legacy
continue;
if (_dict.isSystemTable(tableName, tableSchema, schemaName != null))
continue;
// ignore tables not in list, or not allowed by schemas property
if (tableNames != null
&& !tableNames.contains(tableName.toUpperCase()))
continue;
if (!isAllowedTable(tableSchema, tableName))
continue;
schema = group.getSchema(tableSchema);
if (schema == null)
schema = group.addSchema(tableSchema);
table = schema.getTable(tableName);
if (table == null) {
table = schema.addTable(tableName);
if (_log.isTraceEnabled())
_log.trace(_loc.get("col-table", table));
}
if (_log.isTraceEnabled())
_log.trace(_loc.get("gen-column", cols[i].getName(), table));
if (table.getColumn(cols[i].getName()) == null) {
// It's possible that the original column name was delimited,
// so delimit it and try again
String delimCol = _dict.addDelimiters(cols[i].getName());
if (table.getColumn(delimCol) == null) {
table.importColumn(cols[i]);
}
}
}
}
|
openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/SchemaGenerator.java
|
satd-removal_data_12
|
TODO it might be nice to move these calculations somewhere else since they will need to be reused
@Override
public void handle(Session session, GlowPlayer player, BlockPlacementMessage message) {
if (player == null)
return;
GlowWorld world = player.getWorld();
int x = message.getX();
int z = message.getZ();
int y = message.getY();
switch (message.getDirection()) {
case 0:
--y; break;
case 1:
++y; break;
case 2:
--z; break;
case 3:
++z; break;
case 4:
--x; break;
case 5:
++x; break;
}
// TODO it might be nice to move these calculations somewhere else since they will need to be reused
int chunkX = x / GlowChunk.WIDTH + ((x < 0 && x % GlowChunk.WIDTH != 0) ? -1 : 0);
int chunkZ = z / GlowChunk.HEIGHT + ((z < 0 && z % GlowChunk.HEIGHT != 0) ? -1 : 0);
int localX = (x - chunkX * GlowChunk.WIDTH) % GlowChunk.WIDTH;
int localZ = (z - chunkZ * GlowChunk.HEIGHT) % GlowChunk.HEIGHT;
GlowChunk chunk = world.getChunkManager().getChunk(chunkX, chunkZ);
chunk.setType(localX, localZ, y, Material.WOOD.getId());
// TODO this should also be somewhere else as well... perhaps in the chunk.setType() method itself?
BlockChangeMessage bcmsg = new BlockChangeMessage(x, y, z, Material.WOOD.getId(), 0);
for (GlowPlayer p: world.getRawPlayers()) {
p.getSession().send(bcmsg);
}
}
@Override
public void handle(Session session, GlowPlayer player, BlockPlacementMessage message) {
if (player == null)
return;
GlowWorld world = player.getWorld();
int x = message.getX();
int z = message.getZ();
int y = message.getY();
switch (message.getDirection()) {
case 0:
--y; break;
case 1:
++y; break;
case 2:
--z; break;
case 3:
++z; break;
case 4:
--x; break;
case 5:
++x; break;
}
world.getBlockAt(x, y, z).setType(Material.WOOD);
}
|
src/main/java/net/glowstone/msg/handler/BlockPlacementMessageHandler.java
|
satd-removal_data_13
|
TODO set the owner property
@Override
public void add(IdentityContext context, AttributedType value) {
if (IdentityType.class.isInstance(value)) {
EntityGraph graph = EntityGraph.create(value, config.getIdentityModel());
graph.setProperty(config.getIdentityModel().getIdentityClassProperty(), value.getClass().getName());
graph.persist(getEntityManager(context));
} else if (Relationship.class.isInstance(value)) {
Relationship relationship = (Relationship) value;
EntityGraph graph = EntityGraph.create(relationship, config.getRelationshipModel());
graph.setProperty(config.getRelationshipModel().getRelationshipClassProperty(), relationship.getClass().getName());
// For each of the identities participating in the relationship, create a new node in the graph
Class<?> relationshipIdentityClass = config.getRelationshipModel().getRelationshipMember().getDeclaringClass();
Set<Property<? extends IdentityType>> identityProperties = relationshipMetadata.getRelationshipIdentityProperties(
relationship.getClass());
for (Property<? extends IdentityType> property : identityProperties) {
Object entity = graph.createEntity(relationshipIdentityClass);
graph.createNode(entity, false);
// If the relationship member property is a String, set the identifier as the value
if (String.class.equals(config.getRelationshipModel().getRelationshipMember().getJavaClass())) {
IdentityType relationshipIdentity = property.getValue(relationship);
// We use the convention "Identity ID:Partition ID" to store identity references
// TODO maybe replace this with an IdentityReference instead?
graph.setProperty(config.getRelationshipModel().getRelationshipMember(),
String.format("%s:%s", relationshipIdentity.getId(), relationshipIdentity.getPartition().getId()));
} else {
// Otherwise we set the value to the entity with the specified identifier
AttributedType member = (AttributedType) config.getRelationshipModel().getRelationshipMember().getValue(relationship);
String identifier = member.getId();
Object identityEntity = lookupEntityByParameter(context, config.getIdentityModel(), IdentityType.class, "id", identifier);
graph.setProperty(config.getRelationshipModel().getRelationshipMember(), identityEntity);
}
graph.setProperty(config.getRelationshipModel().getRelationshipDescriptor(), property.getName());
// TODO set the owner property
}
graph.persist(getEntityManager(context));
}
}
@Override
public void add(IdentityContext context, AttributedType attributedType) {
attributedType.setId(context.getIdGenerator().generate());
if (IdentityType.class.isInstance(attributedType)) {
IdentityType identityType = (IdentityType) attributedType;
identityType.setPartition(context.getPartition());
}
EntityManager entityManager = getEntityManager(context);
for (EntityMapper entityMapper : getMapperFor(attributedType.getClass())) {
Object entity = entityMapper.createEntity(attributedType, entityManager);
if (entity != null) {
entityManager.persist(entity);
}
if (Relationship.class.isInstance(attributedType)) {
addRelationshipIdentity(attributedType, entityManager);
}
}
entityManager.flush();
}
|
modules/idm/impl/src/main/java/org/picketlink/idm/jpa/internal/JPAIdentityStore.java
|
satd-removal_data_14
|
TODO: fix this (BATCH-1030)
@Test
public void testFailedStepRestarted() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StepSupport("step1") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
UnexpectedJobExecutionException {
stepExecution.setStatus(BatchStatus.FAILED);
stepExecution.setExitStatus(ExitStatus.FAILED);
jobRepository.update(stepExecution);
}
}), "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
UnexpectedJobExecutionException {
if (fail) {
stepExecution.setStatus(BatchStatus.FAILED);
stepExecution.setExitStatus(ExitStatus.FAILED);
jobRepository.update(stepExecution);
} else {
super.execute(stepExecution);
}
}
})));
flow.setStateTransitions(transitions);
job.setFlow(flow);
job.afterPropertiesSet();
fail = true;
job.execute(jobExecution);
assertEquals(ExitStatus.FAILED, jobExecution.getExitStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
jobRepository.update(jobExecution);
jobExecution = jobRepository.createJobExecution("job", new JobParameters());
fail = false;
job.execute(jobExecution);
assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
// TODO: fix this (BATCH-1030)
// assertEquals(1, jobExecution.getStepExecutions().size());
}
@Test
public void testFailedStepRestarted() throws Exception {
SimpleFlow flow = new SimpleFlow("job");
List<StateTransition> transitions = new ArrayList<StateTransition>();
transitions.add(StateTransition.createStateTransition(new StepState(new StepSupport("step1") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
UnexpectedJobExecutionException {
stepExecution.setStatus(BatchStatus.FAILED);
stepExecution.setExitStatus(ExitStatus.FAILED);
jobRepository.update(stepExecution);
}
}), "step2"));
transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2") {
@Override
public void execute(StepExecution stepExecution) throws JobInterruptedException,
UnexpectedJobExecutionException {
if (fail) {
stepExecution.setStatus(BatchStatus.FAILED);
stepExecution.setExitStatus(ExitStatus.FAILED);
jobRepository.update(stepExecution);
} else {
super.execute(stepExecution);
}
}
})));
flow.setStateTransitions(transitions);
job.setFlow(flow);
job.afterPropertiesSet();
fail = true;
job.execute(jobExecution);
assertEquals(ExitStatus.FAILED, jobExecution.getExitStatus());
assertEquals(2, jobExecution.getStepExecutions().size());
jobRepository.update(jobExecution);
jobExecution = jobRepository.createJobExecution("job", new JobParameters());
fail = false;
job.execute(jobExecution);
assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
assertEquals(1, jobExecution.getStepExecutions().size());
}
|
spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java
|
satd-removal_data_15
|
TODO: debug view for candidate strip needed.
private void updateSuggestions() {
final SuggestedWords suggestions = mSuggestions;
final List<SuggestedWordInfo> suggestedWordInfoList = suggestions.mSuggestedWordInfoList;
clear();
final int paneWidth = getWidth();
final int dividerWidth = mDividers.get(0).getMeasuredWidth();
int x = 0;
int y = 0;
int fromIndex = NUM_CANDIDATES_IN_STRIP;
final int count = Math.min(mWords.size(), suggestions.size());
closeCandidatesPane();
mExpandCandidatesPane.setEnabled(count >= NUM_CANDIDATES_IN_STRIP);
for (int i = 0; i < count; i++) {
final CharSequence word = suggestions.getWord(i);
if (word == null) continue;
final SuggestedWordInfo info = (suggestedWordInfoList != null)
? suggestedWordInfoList.get(i) : null;
final boolean isAutoCorrect = suggestions.mHasMinimalSuggestion
&& ((i == 1 && !suggestions.mTypedWordValid)
|| (i == 0 && suggestions.mTypedWordValid));
// HACK: even if i == 0, we use mColorOther when this suggestion's length is 1
// and there are multiple suggestions, such as the default punctuation list.
// TODO: Need to revisit this logic with bigram suggestions
final boolean isSuggestedCandidate = (i != 0);
final boolean isPunctuationSuggestions = (word.length() == 1 && count > 1);
final TextView tv = mWords.get(i);
// TODO: Reorder candidates in strip as appropriate. The center candidate should hold
// the word when space is typed (valid typed word or auto corrected word).
tv.setTextColor(getCandidateTextColor(isAutoCorrect,
isSuggestedCandidate || isPunctuationSuggestions, info));
tv.setText(getStyledCandidateWord(word, isAutoCorrect));
// TODO: call TextView.setTextScaleX() to fit the candidate in single line.
if (i >= NUM_CANDIDATES_IN_STRIP) {
tv.measure(UNSPECIFIED_MEASURESPEC, UNSPECIFIED_MEASURESPEC);
final int width = tv.getMeasuredWidth();
// TODO: Handle overflow case.
if (dividerWidth + x + width >= paneWidth) {
centeringCandidates(fromIndex, i - 1, x, paneWidth);
x = 0;
y += mCandidateStripHeight;
fromIndex = i;
}
if (x != 0) {
final View divider = mDividers.get(i - NUM_CANDIDATES_IN_STRIP);
addCandidateAt(divider, x, y);
x += dividerWidth;
}
addCandidateAt(tv, x, y);
x += width;
}
if (DBG && info != null) {
final TextView dv = new TextView(getContext(), null);
dv.setTextSize(10.0f);
dv.setTextColor(0xff808080);
dv.setText(info.getDebugString());
// TODO: debug view for candidate strip needed.
// mCandidatesPane.addView(dv);
// LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)dv.getLayoutParams();
// lp.gravity = Gravity.BOTTOM;
}
}
if (x != 0) {
// Centering last candidates row.
centeringCandidates(fromIndex, count - 1, x, paneWidth);
}
}
private void updateSuggestions() {
final SuggestedWords suggestions = mSuggestions;
final List<SuggestedWordInfo> suggestedWordInfoList = suggestions.mSuggestedWordInfoList;
clear();
final int paneWidth = getWidth();
final int dividerWidth = mDividers.get(0).getMeasuredWidth();
final int dividerHeight = mDividers.get(0).getMeasuredHeight();
int x = 0;
int y = 0;
int fromIndex = NUM_CANDIDATES_IN_STRIP;
final int count = Math.min(mWords.size(), suggestions.size());
closeCandidatesPane();
mExpandCandidatesPane.setEnabled(count >= NUM_CANDIDATES_IN_STRIP);
for (int i = 0; i < count; i++) {
final CharSequence suggestion = suggestions.getWord(i);
if (suggestion == null) continue;
final SuggestedWordInfo suggestionInfo = (suggestedWordInfoList != null)
? suggestedWordInfoList.get(i) : null;
final boolean isAutoCorrect = suggestions.mHasMinimalSuggestion
&& ((i == 1 && !suggestions.mTypedWordValid)
|| (i == 0 && suggestions.mTypedWordValid));
// HACK: even if i == 0, we use mColorOther when this suggestion's length is 1
// and there are multiple suggestions, such as the default punctuation list.
// TODO: Need to revisit this logic with bigram suggestions
final boolean isSuggestedCandidate = (i != 0);
final boolean isPunctuationSuggestions = (suggestion.length() == 1 && count > 1);
final TextView word = mWords.get(i);
// TODO: Reorder candidates in strip as appropriate. The center candidate should hold
// the word when space is typed (valid typed word or auto corrected word).
word.setTextColor(getCandidateTextColor(isAutoCorrect,
isSuggestedCandidate || isPunctuationSuggestions, suggestionInfo));
word.setText(getStyledCandidateWord(suggestion, isAutoCorrect));
// TODO: call TextView.setTextScaleX() to fit the candidate in single line.
word.measure(UNSPECIFIED_MEASURESPEC, UNSPECIFIED_MEASURESPEC);
final int width = word.getMeasuredWidth();
final int height = word.getMeasuredHeight();
final TextView info;
if (DBG && suggestionInfo != null
&& !TextUtils.isEmpty(suggestionInfo.getDebugString())) {
info = mInfos.get(i);
info.setText(suggestionInfo.getDebugString());
info.setVisibility(View.VISIBLE);
info.measure(UNSPECIFIED_MEASURESPEC, UNSPECIFIED_MEASURESPEC);
} else {
info = null;
}
if (i < NUM_CANDIDATES_IN_STRIP) {
if (info != null) {
final int infoWidth = info.getMeasuredWidth();
FrameLayoutCompatUtils.placeViewAt(
info, x + width - infoWidth, y, infoWidth, info.getMeasuredHeight());
}
} else {
// TODO: Handle overflow case.
if (dividerWidth + x + width >= paneWidth) {
centeringCandidates(fromIndex, i - 1, x, paneWidth);
x = 0;
y += mCandidateStripHeight;
fromIndex = i;
}
if (x != 0) {
final View divider = mDividers.get(i - NUM_CANDIDATES_IN_STRIP);
mCandidatesPane.addView(divider);
FrameLayoutCompatUtils.placeViewAt(
divider, x, y + (mCandidateStripHeight - dividerHeight) / 2,
dividerWidth, dividerHeight);
x += dividerWidth;
}
mCandidatesPane.addView(word);
FrameLayoutCompatUtils.placeViewAt(
word, x, y + (mCandidateStripHeight - height) / 2, width, height);
if (info != null) {
mCandidatesPane.addView(info);
final int infoWidth = info.getMeasuredWidth();
FrameLayoutCompatUtils.placeViewAt(
info, x + width - infoWidth, y, infoWidth, info.getMeasuredHeight());
}
x += width;
}
}
if (x != 0) {
// Centering last candidates row.
centeringCandidates(fromIndex, count - 1, x, paneWidth);
}
}
|
java/src/com/android/inputmethod/latin/CandidateView.java
|
satd-removal_data_16
|
todo log & ignore
public void run() {
final Selector selector = this.selector;
for (; ;) {
try {
keyLoad = selector.keys().size();
selector.select();
synchronized (selectorWorkQueue) {
while (! selectorWorkQueue.isEmpty()) {
final SelectorTask task = selectorWorkQueue.remove();
try {
task.run(selector);
} catch (Throwable t) {
t.printStackTrace();
// todo log & ignore
}
}
}
final Set<SelectionKey> selectedKeys = selector.selectedKeys();
final Iterator<SelectionKey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
iterator.remove();
try {
key.interestOps(key.interestOps() & (SelectionKey.OP_ACCEPT));
try {
final NioHandle handle = (NioHandle) key.attachment();
handle.getHandlerExecutor().execute(handle.getHandler());
} catch (Throwable t) {
// tough crap
// todo log @ trace
t.printStackTrace();
}
} catch (CancelledKeyException e) {
// todo log @ trace (normal)
// e.printStackTrace();
continue;
}
}
} catch (ClosedSelectorException e) {
// THIS is the "official" signalling mechanism
// todo log @ trace (normal)
// e.printStackTrace();
return;
} catch (IOException e) {
// todo - other I/O errors - should they be fatal?
e.printStackTrace();
}
}
}
public void run() {
final Selector selector = this.selector;
for (; ;) {
try {
keyLoad = selector.keys().size();
selector.select();
synchronized (selectorWorkQueue) {
while (! selectorWorkQueue.isEmpty()) {
final SelectorTask task = selectorWorkQueue.remove();
try {
task.run(selector);
} catch (Throwable t) {
log.trace(t, "NIO selector task failed");
}
}
}
final Set<SelectionKey> selectedKeys = selector.selectedKeys();
final Iterator<SelectionKey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
iterator.remove();
try {
key.interestOps(key.interestOps() & (SelectionKey.OP_ACCEPT));
try {
final NioHandle handle = (NioHandle) key.attachment();
handle.getHandlerExecutor().execute(handle.getHandler());
} catch (Throwable t) {
log.trace(t, "Failed to execute handler");
}
} catch (CancelledKeyException e) {
log.trace("Key %s cancelled", key);
continue;
}
}
} catch (ClosedSelectorException e) {
// THIS is the "official" signalling mechanism
log.trace("Selector %s closed", selector);
return;
} catch (IOException e) {
log.trace(e, "I/O error in selector loop");
}
}
}
|
nio-impl/src/main/java/org/jboss/xnio/core/nio/NioSelectorRunnable.java
|
satd-removal_data_17
|
FIXME Should be refactored when OPENENGSB-1931 is fixed
public void init() {
new Thread() {
@Override
public void run() {
try {
Collection<ConnectorConfiguration> configs;
try {
Map<String, String> emptyMap = Collections.emptyMap();
configs = configPersistence.load(emptyMap);
} catch (InvalidConfigurationException e) {
throw new IllegalStateException(e);
} catch (PersistenceException e) {
throw new IllegalStateException(e);
}
// FIXME Should be refactored when OPENENGSB-1931 is fixed
configs = Collections2.filter(configs, new Predicate<ConfigItem<?>>() {
@Override
public boolean apply(ConfigItem<?> input) {
return input instanceof ConnectorConfiguration;
}
});
for (ConnectorConfiguration c : configs) {
try {
registrationManager.updateRegistration(c.getConnectorId(), c.getContent());
} catch (ConnectorValidationFailedException e) {
throw new IllegalStateException(e);
}
}
} catch (Exception e) {
LOGGER.error("Exception while restoring connectors", e);
}
}
}.start();
}
public void init() {
new Thread() {
@Override
public void run() {
Collection<ConnectorConfiguration> configs;
try {
Map<String, String> emptyMap = Collections.emptyMap();
configs = configPersistence.load(emptyMap);
} catch (InvalidConfigurationException e) {
throw new IllegalStateException(e);
} catch (PersistenceException e) {
throw new IllegalStateException(e);
}
for (ConnectorConfiguration c : configs) {
try {
registrationManager.updateRegistration(c.getConnectorId(), c.getContent());
} catch (ConnectorValidationFailedException e) {
throw new IllegalStateException(e);
}
}
}
}.start();
}
|
components/services/src/main/java/org/openengsb/core/services/internal/ConnectorManagerImpl.java
|
satd-removal_data_18
|
TODO CHECK BIZARE D'AVOIR KER = ENVELOPE
@Override
public void propagate(int evtmask) throws ContradictionException {
int k = set.getKernelSize();
card.updateLowerBound(k, aCause);
int e = set.getEnvelopeSize();
card.updateUpperBound(e, aCause);
if (card.instantiated()) {
int c = card.getValue();
ISet env = set.getEnvelope();
if (c == k) {
// TODO CHECK BIZARE D'AVOIR KER = ENVELOPE
ISet ker = set.getEnvelope();
for (int j=set.getEnvelopeFirstElement(); j!=SetVar.END; j=set.getEnvelopeNextElement()) {
if (!ker.contain(j)) {
set.removeFromEnvelope(j, aCause);
}
}
} else if (c == e) {
for (int j=set.getEnvelopeFirstElement(); j!=SetVar.END; j=set.getEnvelopeNextElement()) {
set.addToKernel(j, aCause);
}
}
}
}
@Override
public void propagate(int evtmask) throws ContradictionException {
int k = set.getKernelSize();
card.updateLowerBound(k, aCause);
int e = set.getEnvelopeSize();
card.updateUpperBound(e, aCause);
if (card.instantiated()) {
int c = card.getValue();
if (c == k) {
for (int j=set.getEnvelopeFirstElement(); j!=SetVar.END; j=set.getEnvelopeNextElement()) {
if (!set.kernelContains(j)) {
set.removeFromEnvelope(j, aCause);
}
}
} else if (c == e) {
for (int j=set.getEnvelopeFirstElement(); j!=SetVar.END; j=set.getEnvelopeNextElement()) {
set.addToKernel(j, aCause);
}
}
}
}
|
choco-solver/src/main/java/solver/constraints/propagators/set/PropCardinality.java
|
satd-removal_data_19
|
TODO: setForeground / startForeground
public void register(final Intent intent) {
Log.d(TAG, "register(" + intent.getAction() + ")");
// TODO: setForeground / startForeground
if (this.helperAPI5s == null) {
this.setForeground(true);
} else {
// TODO: fix me
}
synchronized (this.pendingIOOps) {
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
this.pendingIOOps.add(intent);
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
}
}
public void register(final Intent intent) {
Log.d(TAG, "register(" + intent.getAction() + ")");
// setForeground / startForeground
Notification notification = null;
if (this.helperAPI5s == null) {
this.setForeground(true);
} else {
notification = this.getNotification();
this.helperAPI5s.startForeground(this, NOTIFICATION_PENDING,
notification);
}
if (new ConnectorCommand(intent).getType() == ConnectorCommand.TYPE_SEND) {
if (notification == null) {
notification = this.getNotification();
}
NotificationManager mNotificationMgr = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationMgr.notify(NOTIFICATION_PENDING, notification);
}
synchronized (this.pendingIOOps) {
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
this.pendingIOOps.add(intent);
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
}
}
|
src/de/ub0r/android/websms/connector/common/ConnectorService.java
|
satd-removal_data_20
|
Remove those meaningless options for now. TODO: delete them for good
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setInputMethodSettingsCategoryTitle(R.string.language_selection_title);
setSubtypeEnablerTitle(R.string.select_language);
addPreferencesFromResource(R.xml.prefs);
final Resources res = getResources();
final Context context = getActivity();
mVoicePreference = (ListPreference) findPreference(PREF_VOICE_MODE);
mShowCorrectionSuggestionsPreference =
(ListPreference) findPreference(PREF_SHOW_SUGGESTIONS_SETTING);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mAutoCorrectionThresholdPreference =
(ListPreference) findPreference(PREF_AUTO_CORRECTION_THRESHOLD);
mBigramSuggestion = (CheckBoxPreference) findPreference(PREF_BIGRAM_SUGGESTION);
mBigramPrediction = (CheckBoxPreference) findPreference(PREF_BIGRAM_PREDICTIONS);
mDebugSettingsPreference = findPreference(PREF_DEBUG_SETTINGS);
if (mDebugSettingsPreference != null) {
final Intent debugSettingsIntent = new Intent(Intent.ACTION_MAIN);
debugSettingsIntent.setClassName(
context.getPackageName(), DebugSettings.class.getName());
mDebugSettingsPreference.setIntent(debugSettingsIntent);
}
ensureConsistencyOfAutoCorrectionSettings();
final PreferenceGroup generalSettings =
(PreferenceGroup) findPreference(PREF_GENERAL_SETTINGS);
final PreferenceGroup textCorrectionGroup =
(PreferenceGroup) findPreference(PREF_CORRECTION_SETTINGS);
final PreferenceGroup miscSettings =
(PreferenceGroup) findPreference(PREF_MISC_SETTINGS);
final boolean showVoiceKeyOption = res.getBoolean(
R.bool.config_enable_show_voice_key_option);
if (!showVoiceKeyOption) {
generalSettings.removePreference(mVoicePreference);
}
final PreferenceGroup advancedSettings =
(PreferenceGroup) findPreference(PREF_ADVANCED_SETTINGS);
// Remove those meaningless options for now. TODO: delete them for good
advancedSettings.removePreference(findPreference(PREF_BIGRAM_SUGGESTION));
advancedSettings.removePreference(findPreference(PREF_KEY_ENABLE_SPAN_INSERT));
if (!VibratorUtils.getInstance(context).hasVibrator()) {
generalSettings.removePreference(findPreference(PREF_VIBRATE_ON));
if (null != advancedSettings) { // Theoretically advancedSettings cannot be null
advancedSettings.removePreference(findPreference(PREF_VIBRATION_DURATION_SETTINGS));
}
}
final boolean showPopupOption = res.getBoolean(
R.bool.config_enable_show_popup_on_keypress_option);
if (!showPopupOption) {
generalSettings.removePreference(findPreference(PREF_POPUP_ON));
}
final boolean showBigramSuggestionsOption = res.getBoolean(
R.bool.config_enable_next_word_suggestions_option);
if (!showBigramSuggestionsOption) {
textCorrectionGroup.removePreference(mBigramSuggestion);
if (null != mBigramPrediction) {
textCorrectionGroup.removePreference(mBigramPrediction);
}
}
final CheckBoxPreference includeOtherImesInLanguageSwitchList =
(CheckBoxPreference)findPreference(PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST);
includeOtherImesInLanguageSwitchList.setEnabled(
!SettingsValues.isLanguageSwitchKeySupressed(prefs));
mKeyPreviewPopupDismissDelay =
(ListPreference)findPreference(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY);
final String[] entries = new String[] {
res.getString(R.string.key_preview_popup_dismiss_no_delay),
res.getString(R.string.key_preview_popup_dismiss_default_delay),
};
final String popupDismissDelayDefaultValue = Integer.toString(res.getInteger(
R.integer.config_key_preview_linger_timeout));
mKeyPreviewPopupDismissDelay.setEntries(entries);
mKeyPreviewPopupDismissDelay.setEntryValues(
new String[] { "0", popupDismissDelayDefaultValue });
if (null == mKeyPreviewPopupDismissDelay.getValue()) {
mKeyPreviewPopupDismissDelay.setValue(popupDismissDelayDefaultValue);
}
mKeyPreviewPopupDismissDelay.setEnabled(
SettingsValues.isKeyPreviewPopupEnabled(prefs, res));
final PreferenceScreen dictionaryLink =
(PreferenceScreen) findPreference(PREF_CONFIGURE_DICTIONARIES_KEY);
final Intent intent = dictionaryLink.getIntent();
final int number = context.getPackageManager().queryIntentActivities(intent, 0).size();
if (0 >= number) {
textCorrectionGroup.removePreference(dictionaryLink);
}
final boolean showUsabilityStudyModeOption =
res.getBoolean(R.bool.config_enable_usability_study_mode_option)
|| ProductionFlag.IS_EXPERIMENTAL || ENABLE_EXPERIMENTAL_SETTINGS;
final Preference usabilityStudyPref = findPreference(PREF_USABILITY_STUDY_MODE);
if (!showUsabilityStudyModeOption) {
if (usabilityStudyPref != null) {
miscSettings.removePreference(usabilityStudyPref);
}
}
if (ProductionFlag.IS_EXPERIMENTAL) {
if (usabilityStudyPref instanceof CheckBoxPreference) {
CheckBoxPreference checkbox = (CheckBoxPreference)usabilityStudyPref;
checkbox.setChecked(prefs.getBoolean(PREF_USABILITY_STUDY_MODE, true));
checkbox.setSummary(R.string.settings_warning_researcher_mode);
}
}
mKeypressVibrationDurationSettingsPref =
(PreferenceScreen) findPreference(PREF_VIBRATION_DURATION_SETTINGS);
if (mKeypressVibrationDurationSettingsPref != null) {
mKeypressVibrationDurationSettingsPref.setOnPreferenceClickListener(
new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference arg0) {
showKeypressVibrationDurationSettingsDialog();
return true;
}
});
updateKeypressVibrationDurationSettingsSummary(prefs, res);
}
mKeypressSoundVolumeSettingsPref =
(PreferenceScreen) findPreference(PREF_KEYPRESS_SOUND_VOLUME);
if (mKeypressSoundVolumeSettingsPref != null) {
mKeypressSoundVolumeSettingsPref.setOnPreferenceClickListener(
new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference arg0) {
showKeypressSoundVolumeSettingDialog();
return true;
}
});
updateKeypressSoundVolumeSummary(prefs, res);
}
refreshEnablingsOfKeypressSoundAndVibrationSettings(prefs, res);
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setInputMethodSettingsCategoryTitle(R.string.language_selection_title);
setSubtypeEnablerTitle(R.string.select_language);
addPreferencesFromResource(R.xml.prefs);
final Resources res = getResources();
final Context context = getActivity();
mVoicePreference = (ListPreference) findPreference(PREF_VOICE_MODE);
mShowCorrectionSuggestionsPreference =
(ListPreference) findPreference(PREF_SHOW_SUGGESTIONS_SETTING);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mAutoCorrectionThresholdPreference =
(ListPreference) findPreference(PREF_AUTO_CORRECTION_THRESHOLD);
mBigramPrediction = (CheckBoxPreference) findPreference(PREF_BIGRAM_PREDICTIONS);
mDebugSettingsPreference = findPreference(PREF_DEBUG_SETTINGS);
if (mDebugSettingsPreference != null) {
final Intent debugSettingsIntent = new Intent(Intent.ACTION_MAIN);
debugSettingsIntent.setClassName(
context.getPackageName(), DebugSettings.class.getName());
mDebugSettingsPreference.setIntent(debugSettingsIntent);
}
ensureConsistencyOfAutoCorrectionSettings();
final PreferenceGroup generalSettings =
(PreferenceGroup) findPreference(PREF_GENERAL_SETTINGS);
final PreferenceGroup textCorrectionGroup =
(PreferenceGroup) findPreference(PREF_CORRECTION_SETTINGS);
final PreferenceGroup miscSettings =
(PreferenceGroup) findPreference(PREF_MISC_SETTINGS);
final boolean showVoiceKeyOption = res.getBoolean(
R.bool.config_enable_show_voice_key_option);
if (!showVoiceKeyOption) {
generalSettings.removePreference(mVoicePreference);
}
if (!VibratorUtils.getInstance(context).hasVibrator()) {
final PreferenceGroup advancedSettings =
(PreferenceGroup) findPreference(PREF_ADVANCED_SETTINGS);
generalSettings.removePreference(findPreference(PREF_VIBRATE_ON));
if (null != advancedSettings) { // Theoretically advancedSettings cannot be null
advancedSettings.removePreference(findPreference(PREF_VIBRATION_DURATION_SETTINGS));
}
}
final boolean showPopupOption = res.getBoolean(
R.bool.config_enable_show_popup_on_keypress_option);
if (!showPopupOption) {
generalSettings.removePreference(findPreference(PREF_POPUP_ON));
}
final CheckBoxPreference includeOtherImesInLanguageSwitchList =
(CheckBoxPreference)findPreference(PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST);
includeOtherImesInLanguageSwitchList.setEnabled(
!SettingsValues.isLanguageSwitchKeySupressed(prefs));
mKeyPreviewPopupDismissDelay =
(ListPreference)findPreference(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY);
final String[] entries = new String[] {
res.getString(R.string.key_preview_popup_dismiss_no_delay),
res.getString(R.string.key_preview_popup_dismiss_default_delay),
};
final String popupDismissDelayDefaultValue = Integer.toString(res.getInteger(
R.integer.config_key_preview_linger_timeout));
mKeyPreviewPopupDismissDelay.setEntries(entries);
mKeyPreviewPopupDismissDelay.setEntryValues(
new String[] { "0", popupDismissDelayDefaultValue });
if (null == mKeyPreviewPopupDismissDelay.getValue()) {
mKeyPreviewPopupDismissDelay.setValue(popupDismissDelayDefaultValue);
}
mKeyPreviewPopupDismissDelay.setEnabled(
SettingsValues.isKeyPreviewPopupEnabled(prefs, res));
final PreferenceScreen dictionaryLink =
(PreferenceScreen) findPreference(PREF_CONFIGURE_DICTIONARIES_KEY);
final Intent intent = dictionaryLink.getIntent();
final int number = context.getPackageManager().queryIntentActivities(intent, 0).size();
if (0 >= number) {
textCorrectionGroup.removePreference(dictionaryLink);
}
final boolean showUsabilityStudyModeOption =
res.getBoolean(R.bool.config_enable_usability_study_mode_option)
|| ProductionFlag.IS_EXPERIMENTAL || ENABLE_EXPERIMENTAL_SETTINGS;
final Preference usabilityStudyPref = findPreference(PREF_USABILITY_STUDY_MODE);
if (!showUsabilityStudyModeOption) {
if (usabilityStudyPref != null) {
miscSettings.removePreference(usabilityStudyPref);
}
}
if (ProductionFlag.IS_EXPERIMENTAL) {
if (usabilityStudyPref instanceof CheckBoxPreference) {
CheckBoxPreference checkbox = (CheckBoxPreference)usabilityStudyPref;
checkbox.setChecked(prefs.getBoolean(PREF_USABILITY_STUDY_MODE, true));
checkbox.setSummary(R.string.settings_warning_researcher_mode);
}
}
mKeypressVibrationDurationSettingsPref =
(PreferenceScreen) findPreference(PREF_VIBRATION_DURATION_SETTINGS);
if (mKeypressVibrationDurationSettingsPref != null) {
mKeypressVibrationDurationSettingsPref.setOnPreferenceClickListener(
new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference arg0) {
showKeypressVibrationDurationSettingsDialog();
return true;
}
});
updateKeypressVibrationDurationSettingsSummary(prefs, res);
}
mKeypressSoundVolumeSettingsPref =
(PreferenceScreen) findPreference(PREF_KEYPRESS_SOUND_VOLUME);
if (mKeypressSoundVolumeSettingsPref != null) {
mKeypressSoundVolumeSettingsPref.setOnPreferenceClickListener(
new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference arg0) {
showKeypressSoundVolumeSettingDialog();
return true;
}
});
updateKeypressSoundVolumeSummary(prefs, res);
}
refreshEnablingsOfKeypressSoundAndVibrationSettings(prefs, res);
}
|
java/src/com/android/inputmethod/latin/Settings.java
|
satd-removal_data_21
|
TODO: include last social snippet after update
private Dialog createNameDialog() {
// Build set of all available display names
final ArrayList<ValuesDelta> allNames = new ArrayList<ValuesDelta>();
for (EntityDelta entity : this.mEntities) {
final ArrayList<ValuesDelta> displayNames = entity
.getMimeEntries(StructuredName.CONTENT_ITEM_TYPE);
allNames.addAll(displayNames);
}
// Wrap our context to inflate list items using correct theme
final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
final LayoutInflater dialogInflater = this.getLayoutInflater().cloneInContext(dialogContext);
final ListAdapter nameAdapter = new ArrayAdapter<ValuesDelta>(this,
android.R.layout.simple_list_item_1, allNames) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = dialogInflater.inflate(
android.R.layout.simple_expandable_list_item_1, parent, false);
}
final ValuesDelta structuredName = this.getItem(position);
final String displayName = structuredName.getAsString(StructuredName.DISPLAY_NAME);
((TextView)convertView).setText(displayName);
return convertView;
}
};
final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// User picked display name, so make super-primary
final ValuesDelta structuredName = allNames.get(which);
structuredName.put(Data.IS_PRIMARY, 1);
structuredName.put(Data.IS_SUPER_PRIMARY, 1);
// TODO: include last social snippet after update
final String displayName = structuredName.getAsString(StructuredName.DISPLAY_NAME);
}
};
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.dialog_primary_name);
builder.setSingleChoiceItems(nameAdapter, 0, clickListener);
return builder.create();
}
private Dialog createNameDialog() {
// Build set of all available display names
final ArrayList<ValuesDelta> allNames = new ArrayList<ValuesDelta>();
for (EntityDelta entity : mState) {
final ArrayList<ValuesDelta> displayNames = entity
.getMimeEntries(StructuredName.CONTENT_ITEM_TYPE);
allNames.addAll(displayNames);
}
// Wrap our context to inflate list items using correct theme
final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
final LayoutInflater dialogInflater = this.getLayoutInflater()
.cloneInContext(dialogContext);
final ListAdapter nameAdapter = new ArrayAdapter<ValuesDelta>(this,
android.R.layout.simple_list_item_1, allNames) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = dialogInflater.inflate(android.R.layout.simple_list_item_1,
parent, false);
}
final ValuesDelta structuredName = this.getItem(position);
final String displayName = structuredName.getAsString(StructuredName.DISPLAY_NAME);
((TextView)convertView).setText(displayName);
return convertView;
}
};
final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// User picked display name, so make super-primary
final ValuesDelta structuredName = allNames.get(which);
structuredName.put(Data.IS_PRIMARY, 1);
structuredName.put(Data.IS_SUPER_PRIMARY, 1);
// Update header based on edited values
bindHeader();
}
};
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.dialog_primary_name);
builder.setSingleChoiceItems(nameAdapter, 0, clickListener);
return builder.create();
}
|
src/com/android/contacts/ui/EditContactActivity.java
|
satd-removal_data_22
|
todo: should support more that List/Set
@SuppressWarnings("unchecked")
public void injectValueIntoField(Object instance, InvocationProviders invocationProviders, AeshContext aeshContext,
boolean doValidation) throws OptionValidatorException {
if(converter == null || instance == null)
return;
try {
Field field = getField(instance.getClass(), fieldName);
if(!Modifier.isPublic(field.getModifiers()))
field.setAccessible(true);
if(!Modifier.isPublic(instance.getClass().getModifiers())) {
Constructor constructor = instance.getClass().getDeclaredConstructor();
if(constructor != null)
constructor.setAccessible(true);
}
if(optionType == OptionType.NORMAL || optionType == OptionType.BOOLEAN || optionType == OptionType.ARGUMENT) {
if(getValue() != null)
field.set(instance, doConvert(getValue(), invocationProviders, instance, aeshContext, doValidation));
else if(defaultValues.size() > 0) {
field.set(instance, doConvert(defaultValues.get(0), invocationProviders, instance, aeshContext, doValidation));
}
}
else if(optionType == OptionType.LIST || optionType == OptionType.ARGUMENTS) {
if(field.getType().isInterface() || Modifier.isAbstract(field.getType().getModifiers())) {
if(Set.class.isAssignableFrom(field.getType())) {
Set tmpSet = new HashSet<>();
if(values.size() > 0) {
for(String in : values)
tmpSet.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation));
}
else if(defaultValues.size() > 0) {
for(String in : defaultValues)
tmpSet.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation));
}
field.set(instance, tmpSet);
}
else if(List.class.isAssignableFrom(field.getType())) {
List tmpList = new ArrayList();
if(values.size() > 0) {
for(String in : values)
tmpList.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation));
}
else if(defaultValues.size() > 0) {
for(String in : defaultValues)
tmpList.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation));
}
field.set(instance, tmpList);
}
//todo: should support more that List/Set
}
else {
Collection tmpInstance = (Collection) field.getType().newInstance();
if(values.size() > 0) {
for(String in : values)
tmpInstance.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation));
}
else if(defaultValues.size() > 0) {
for(String in : defaultValues)
tmpInstance.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation));
}
field.set(instance, tmpInstance);
}
}
else if(optionType == OptionType.GROUP) {
if(field.getType().isInterface() || Modifier.isAbstract(field.getType().getModifiers())) {
Map<String, Object> tmpMap = newHashMap();
for(String propertyKey : properties.keySet())
tmpMap.put(propertyKey,doConvert(properties.get(propertyKey), invocationProviders, instance, aeshContext, doValidation));
field.set(instance, tmpMap);
}
else {
Map<String,Object> tmpMap = (Map<String,Object>) field.getType().newInstance();
for(String propertyKey : properties.keySet())
tmpMap.put(propertyKey,doConvert(properties.get(propertyKey), invocationProviders, instance, aeshContext, doValidation));
field.set(instance, tmpMap);
}
}
}
catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InstantiationException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void injectValueIntoField(Object instance, InvocationProviders invocationProviders, AeshContext aeshContext,
boolean doValidation) throws OptionValidatorException {
if(converter == null || instance == null)
return;
try {
Field field = getField(instance.getClass(), fieldName);
if(!Modifier.isPublic(field.getModifiers()))
field.setAccessible(true);
if(!Modifier.isPublic(instance.getClass().getModifiers())) {
Constructor constructor = instance.getClass().getDeclaredConstructor();
if(constructor != null)
constructor.setAccessible(true);
}
if(optionType == OptionType.NORMAL || optionType == OptionType.BOOLEAN || optionType == OptionType.ARGUMENT) {
if(getValue() != null)
field.set(instance, doConvert(getValue(), invocationProviders, instance, aeshContext, doValidation));
else if(defaultValues.size() > 0) {
field.set(instance, doConvert(defaultValues.get(0), invocationProviders, instance, aeshContext, doValidation));
}
}
else if(optionType == OptionType.LIST || optionType == OptionType.ARGUMENTS) {
Collection tmpSet = initializeCollection(field);
if(values.size() > 0) {
for(String in : values)
tmpSet.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation));
}
else if(defaultValues.size() > 0) {
for(String in : defaultValues)
tmpSet.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation));
}
field.set(instance, tmpSet);
}
else if(optionType == OptionType.GROUP) {
if(field.getType().isInterface() || Modifier.isAbstract(field.getType().getModifiers())) {
Map<String, Object> tmpMap = newHashMap();
for(String propertyKey : properties.keySet())
tmpMap.put(propertyKey,doConvert(properties.get(propertyKey), invocationProviders, instance, aeshContext, doValidation));
field.set(instance, tmpMap);
}
else {
Map<String,Object> tmpMap = (Map<String,Object>) field.getType().newInstance();
for(String propertyKey : properties.keySet())
tmpMap.put(propertyKey,doConvert(properties.get(propertyKey), invocationProviders, instance, aeshContext, doValidation));
field.set(instance, tmpMap);
}
}
}
catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InstantiationException e) {
e.printStackTrace();
}
}
|
src/main/java/org/aesh/command/impl/internal/ProcessedOption.java
|
satd-removal_data_23
|
TODO: Confirm correct delete policy for exchange
private void onExchange() {
Account account = SetupData.getAccount();
HostAuth recvAuth = account.getOrCreateHostAuthRecv(this);
recvAuth.setConnection(HostAuth.SCHEME_EAS, recvAuth.mAddress, recvAuth.mPort,
recvAuth.mFlags | HostAuth.FLAG_SSL);
HostAuth sendAuth = account.getOrCreateHostAuthSend(this);
sendAuth.setConnection(HostAuth.SCHEME_EAS, sendAuth.mAddress, sendAuth.mPort,
sendAuth.mFlags | HostAuth.FLAG_SSL);
// TODO: Confirm correct delete policy for exchange
account.setDeletePolicy(Account.DELETE_POLICY_ON_DELETE);
account.setSyncInterval(Account.CHECK_INTERVAL_PUSH);
account.setSyncLookback(1);
SetupData.setCheckSettingsMode(SetupData.CHECK_AUTODISCOVER);
AccountSetupExchange.actionIncomingSettings(this, SetupData.getFlowMode(), account);
finish();
}
private void onExchange() {
Account account = SetupData.getAccount();
HostAuth recvAuth = account.getOrCreateHostAuthRecv(this);
recvAuth.setConnection(HostAuth.SCHEME_EAS, recvAuth.mAddress, recvAuth.mPort,
recvAuth.mFlags | HostAuth.FLAG_SSL);
HostAuth sendAuth = account.getOrCreateHostAuthSend(this);
sendAuth.setConnection(HostAuth.SCHEME_EAS, sendAuth.mAddress, sendAuth.mPort,
sendAuth.mFlags | HostAuth.FLAG_SSL);
AccountSetupBasics.setFlagsForProtocol(account, HostAuth.SCHEME_EAS);
SetupData.setCheckSettingsMode(SetupData.CHECK_AUTODISCOVER);
AccountSetupExchange.actionIncomingSettings(this, SetupData.getFlowMode(), account);
finish();
}
|
src/com/android/email/activity/setup/AccountSetupAccountType.java
|
satd-removal_data_24
|
TODO: Log exception
public void performSimpleAction(SimpleSessionAction action) {
final Session session = sessionManager.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
action.perform(session);
tx.commit();
} catch (Exception ex) {
//TODO: Log exception
if (tx != null) {
tx.rollback();
}
} finally {
session.close();
}
}
public void performSimpleAction(SimpleSessionAction action) {
final Session session = sessionManager.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
action.perform(session);
tx.commit();
} catch (Exception ex) {
if (tx != null) {
tx.rollback();
}
throw new AtomDatabaseException("Failure performing hibernate action: " + action.toString(), ex);
} finally {
session.close();
}
}
|
adapters/hibernate/src/main/java/org/atomhopper/hibernate/HibernateFeedRepository.java
|
satd-removal_data_25
|
TODO: THIS IS INEFFICIENT BECAUSE FOR EACH PROPERTY WE DITHER AGAIN
@Override
public void addToLaserJob(LaserJob job, GraphicSet objects)
{
//TODO
for (LaserProperty prop : this.getLaserProperties())
{
Rectangle2D bb = objects.getBoundingBox();
if (bb != null && bb.getWidth() > 0 && bb.getHeight() > 0)
{
BufferedImage scaledImg = new BufferedImage((int) bb.getWidth(), (int) bb.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaledImg.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, scaledImg.getWidth(), scaledImg.getHeight());
g.setClip(0, 0, scaledImg.getWidth(), scaledImg.getHeight());
if (objects.getTransform() != null)
{
Rectangle2D origBB = objects.getOriginalBoundingBox();
Rectangle2D targetBB = new Rectangle(0, 0, scaledImg.getWidth(), scaledImg.getHeight());
g.setTransform(Helper.getTransform(origBB, targetBB));
}
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
for (GraphicObject o : objects)
{
o.render(g);
}
BufferedImageAdapter ad = new BufferedImageAdapter(scaledImg, invertColors);
ad.setColorShift(this.getColorShift());
BlackWhiteRaster bw = new BlackWhiteRaster(ad, this.getDitherAlgorithm());
//TODO: THIS IS INEFFICIENT BECAUSE FOR EACH PROPERTY WE DITHER AGAIN
job.getRasterPart().addImage(bw, prop, new Point((int) bb.getX(), (int) bb.getY()));
}
}
}
@Override
public void addToLaserJob(LaserJob job, GraphicSet set)
{
//Decompose Objects if their distance is big enough
for (GraphicSet objects : this.decompose(set))
{
Rectangle2D bb = objects.getBoundingBox();
if (bb != null && bb.getWidth() > 0 && bb.getHeight() > 0)
{
//First render them on an empty image
BufferedImage scaledImg = new BufferedImage((int) bb.getWidth(), (int) bb.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaledImg.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, scaledImg.getWidth(), scaledImg.getHeight());
g.setClip(0, 0, scaledImg.getWidth(), scaledImg.getHeight());
if (objects.getTransform() != null)
{
Rectangle2D origBB = objects.getOriginalBoundingBox();
Rectangle2D targetBB = new Rectangle(0, 0, scaledImg.getWidth(), scaledImg.getHeight());
g.setTransform(Helper.getTransform(origBB, targetBB));
}
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
for (GraphicObject o : objects)
{
o.render(g);
}
//Then dither this image
BufferedImageAdapter ad = new BufferedImageAdapter(scaledImg, invertColors);
ad.setColorShift(this.getColorShift());
BlackWhiteRaster bw = new BlackWhiteRaster(ad, this.getDitherAlgorithm());
for (LaserProperty prop : this.getLaserProperties())
{//and add it to the raster part as often as defined in the profile
job.getRasterPart().addImage(bw, prop, new Point((int) bb.getX(), (int) bb.getY()));
}
}
}
}
|
src/com/t_oster/visicut/model/RasterProfile.java
|
satd-removal_data_26
|
todo - also allow src from files here
public void execute() throws BuildException {
log("execute()", Project.MSG_VERBOSE);
command = command.trim();
try {
if (srcFile == null && command.length() == 0
&& filesets.isEmpty()) {
throw new BuildException("Source file does not exist!", getLocation());
}
if (srcFile != null && !srcFile.exists()) {
throw new BuildException("Source file does not exist!", getLocation());
}
// deal with the filesets
for (int i = 0; i < filesets.size(); i++) {
FileSet fs = (FileSet) filesets.elementAt(i);
DirectoryScanner ds = fs.getDirectoryScanner(getProject());
File srcDir = fs.getDir(getProject());
String[] srcFiles = ds.getIncludedFiles();
}
try {
PrintStream out = System.out;
try {
if (output != null) {
log("Opening PrintStream to output file " + output,
Project.MSG_VERBOSE);
out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream(output
.getAbsolutePath(),
append)));
}
//todo - also allow src from files here
if (command == null) {
command = getText(new BufferedReader(new FileReader(srcFile)));
}
if (command != null) {
execGroovy(command,out);
} else {
throw new BuildException("Source file does not exist!", getLocation());
}
} finally {
if (out != null && out != System.out) {
out.close();
}
}
} catch (IOException e) {
throw new BuildException(e, getLocation());
}
log("statements executed successfully");
} finally{}
}
public void execute() throws BuildException {
log("execute()", Project.MSG_VERBOSE);
command = command.trim();
try {
if (srcFile == null && command.length() == 0
&& filesets.isEmpty()) {
throw new BuildException("Source file does not exist!", getLocation());
}
if (srcFile != null && !srcFile.exists()) {
throw new BuildException("Source file does not exist!", getLocation());
}
// deal with the filesets
for (int i = 0; i < filesets.size(); i++) {
FileSet fs = (FileSet) filesets.elementAt(i);
DirectoryScanner ds = fs.getDirectoryScanner(getProject());
File srcDir = fs.getDir(getProject());
String[] srcFiles = ds.getIncludedFiles();
}
try {
PrintStream out = System.out;
try {
if (output != null) {
log("Opening PrintStream to output file " + output,
Project.MSG_VERBOSE);
out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream(output
.getAbsolutePath(),
append)));
}
// if there are no groovy statements between the enclosing Groovy tags
// then read groovy statements in from a text file using the src attribute
if (command == null || command.trim().length() == 0) {
command = getText(new BufferedReader(new FileReader(srcFile)));
}
if (command != null) {
execGroovy(command,out);
} else {
throw new BuildException("Source file does not exist!", getLocation());
}
} finally {
if (out != null && out != System.out) {
out.close();
}
}
} catch (IOException e) {
throw new BuildException(e, getLocation());
}
log("statements executed successfully");
} finally{}
}
|
src/main/org/codehaus/groovy/ant/Groovy.java
|
satd-removal_data_27
|
TODO add uninitialized entities immediately again
public Iterator<Move> moveIterator(final Object planningEntity) {
scoreDirector.beforeEntityAdded(planningEntity);
// TODO add uninitialized entities immediately again
scoreDirector.afterEntityAdded(planningEntity);
if (planningValueWalkerList.size() == 1) {
PlanningValueWalker planningValueWalker = planningValueWalkerList.iterator().next();
return planningValueWalker.moveIterator(planningEntity);
} else {
final List<Iterator<Move>> moveIteratorList = new ArrayList<Iterator<Move>>(planningValueWalkerList.size());
final List<Move> composedMoveList = new ArrayList<Move>(planningValueWalkerList.size());
boolean moveIteratorIsFirst = true;
for (PlanningValueWalker planningValueWalker : planningValueWalkerList) {
Iterator<Move> moveIterator = planningValueWalker.moveIterator(planningEntity);
moveIteratorList.add(moveIterator);
Move initialMove;
if (moveIteratorIsFirst) {
// The first moveIterator 's next() call will be done by the new Iterator 's next() call
initialMove = null;
moveIteratorIsFirst = false;
} else {
if (!moveIterator.hasNext()) {
// TODO the algorithms should be able to cope with that. Mind the use of .walkerList.get(j)
throw new IllegalStateException("The planning entity class ("
+ planningEntityDescriptor.getPlanningEntityClass() + ") for planning variable ("
+ planningValueWalker.getPlanningVariableDescriptor().getVariableName()
+ ") has an empty planning value range for planning entity (" + planningEntity + ").");
}
initialMove = moveIterator.next();
}
composedMoveList.add(initialMove);
}
return new Iterator<Move>() {
public boolean hasNext() {
for (Iterator<Move> moveIterator : moveIteratorList) {
if (moveIterator.hasNext()) {
return true;
}
}
// All levels are maxed out
return false;
}
public Move next() {
// Find the level to increment (for example in 115999)
for (int i = 0; i < moveIteratorList.size(); i++) {
Iterator<Move> moveIterator = moveIteratorList.get(i);
if (moveIterator.hasNext()) {
// Increment that level (for example 5 in 115999)
composedMoveList.set(i, moveIterator.next());
// Do not touch the higher levels (for example each 1 in 115999)
break;
} else {
// Reset a lower level (for example each 9 in 115999)
moveIterator = planningValueWalkerList.get(i).moveIterator(planningEntity);
moveIteratorList.set(i, moveIterator);
composedMoveList.set(i, moveIterator.next());
}
}
return new CompositeMove(new ArrayList<Move>(composedMoveList));
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
public Iterator<Move> moveIterator(final Object planningEntity) {
if (planningValueWalkerList.size() == 1) {
PlanningValueWalker planningValueWalker = planningValueWalkerList.iterator().next();
return planningValueWalker.moveIterator(planningEntity);
} else {
final List<Iterator<Move>> moveIteratorList = new ArrayList<Iterator<Move>>(planningValueWalkerList.size());
final List<Move> composedMoveList = new ArrayList<Move>(planningValueWalkerList.size());
boolean moveIteratorIsFirst = true;
for (PlanningValueWalker planningValueWalker : planningValueWalkerList) {
Iterator<Move> moveIterator = planningValueWalker.moveIterator(planningEntity);
moveIteratorList.add(moveIterator);
Move initialMove;
if (moveIteratorIsFirst) {
// The first moveIterator 's next() call will be done by the new Iterator 's next() call
initialMove = null;
moveIteratorIsFirst = false;
} else {
if (!moveIterator.hasNext()) {
// TODO the algorithms should be able to cope with that. Mind the use of .walkerList.get(j)
throw new IllegalStateException("The planning entity class ("
+ planningEntityDescriptor.getPlanningEntityClass() + ") for planning variable ("
+ planningValueWalker.getPlanningVariableDescriptor().getVariableName()
+ ") has an empty planning value range for planning entity (" + planningEntity + ").");
}
initialMove = moveIterator.next();
}
composedMoveList.add(initialMove);
}
return new Iterator<Move>() {
public boolean hasNext() {
for (Iterator<Move> moveIterator : moveIteratorList) {
if (moveIterator.hasNext()) {
return true;
}
}
// All levels are maxed out
return false;
}
public Move next() {
// Find the level to increment (for example in 115999)
for (int i = 0; i < moveIteratorList.size(); i++) {
Iterator<Move> moveIterator = moveIteratorList.get(i);
if (moveIterator.hasNext()) {
// Increment that level (for example 5 in 115999)
composedMoveList.set(i, moveIterator.next());
// Do not touch the higher levels (for example each 1 in 115999)
break;
} else {
// Reset a lower level (for example each 9 in 115999)
moveIterator = planningValueWalkerList.get(i).moveIterator(planningEntity);
moveIteratorList.set(i, moveIterator);
composedMoveList.set(i, moveIterator.next());
}
}
return new CompositeMove(new ArrayList<Move>(composedMoveList));
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
|
drools-planner-core/src/main/java/org/drools/planner/core/heuristic/selector/variable/PlanningVariableWalker.java
|
satd-removal_data_28
|
FIXME throw assertion exception if constraintValidatorType == null
private static Class<?> extractType(Class<? extends ConstraintValidator<?, ?>> validator) {
Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
Type constraintValidatorType = resolveTypes( resolvedTypes, validator );
//we now have all bind from a type to its resolution at one level
//FIXME throw assertion exception if constraintValidatorType == null
Type validatorType = ( ( ParameterizedType ) constraintValidatorType ).getActualTypeArguments()[VALIDATOR_TYPE_INDEX];
while ( resolvedTypes.containsKey( validatorType ) ) {
validatorType = resolvedTypes.get( validatorType );
}
//FIXME raise an exception if validatorType is not a class
return ( Class<?> ) validatorType;
}
private static Class<?> extractType(Class<? extends ConstraintValidator<?, ?>> validator) {
Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
Type constraintValidatorType = resolveTypes( resolvedTypes, validator );
//we now have all bind from a type to its resolution at one level
Type validatorType = ( ( ParameterizedType ) constraintValidatorType ).getActualTypeArguments()[VALIDATOR_TYPE_INDEX];
if ( validatorType == null ) {
throw new ValidationException( "Null is an invalid type for a constraint validator." );
}
else if ( validatorType instanceof GenericArrayType ) {
validatorType = Array.class;
}
while ( resolvedTypes.containsKey( validatorType ) ) {
validatorType = resolvedTypes.get( validatorType );
}
//FIXME raise an exception if validatorType is not a class
return ( Class<?> ) validatorType;
}
|
hibernate-validator/src/main/java/org/hibernate/validation/util/ValidatorTypeHelper.java
|
satd-removal_data_29
|
TODO group by ANKI
private void setOutputProductsGridContent(final ViewDefinitionState viewDefinitionState, final Entity order) {
GridComponent outputProducts = (GridComponent) viewDefinitionState.getComponentByReference("outputProductsGrid");
List<Entity> outputProductsList = new ArrayList<Entity>();
for (Entity productionRecord : order.getHasManyField("productionRecords")) {
outputProductsList.addAll(productionRecord.getHasManyField("recordOperationProductOutComponents"));
}
Collections.sort(outputProductsList, new EntityProductInOutComparator());
outputProducts.setEntities(outputProductsList);
outputProducts.setVisible(true);
// TODO group by ANKI
}
private void setOutputProductsGridContent(final ViewDefinitionState viewDefinitionState, final Entity order) {
GridComponent outputProducts = (GridComponent) viewDefinitionState.getComponentByReference("outputProductsGrid");
List<Entity> outputProductsList = new ArrayList<Entity>();
for (Entity productionRecord : order.getHasManyField("productionRecords")) {
outputProductsList.addAll(productionRecord.getHasManyField("recordOperationProductOutComponents"));
}
Collections.sort(outputProductsList, new EntityProductInOutComparator());
outputProducts.setEntities(productionBalanceReportDataService.groupProductInOutComponentsByProduct(outputProductsList));
outputProducts.setVisible(true);
}
|
mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/ProductionBalanceViewService.java
|
satd-removal_data_30
|
todo: HTTPS values
public void processAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws PortletException, IOException {
String mode = actionRequest.getParameter("mode");
WebContainer container = PortletManager.getCurrentWebContainer(actionRequest);
String server = "generic";
if(container instanceof JettyContainer) {
server = "jetty";
}
actionResponse.setRenderParameter("server", server);
if(mode.equals("new")) {
// User selected to add a new connector, need to show criteria portlet
actionResponse.setRenderParameter("mode", "new");
String protocol = actionRequest.getParameter("protocol");
actionResponse.setRenderParameter("protocol", protocol);
} else if(mode.equals("add")) { // User just submitted the form to add a new connector
// Get submitted values
//todo: lots of validation
String protocol = actionRequest.getParameter("protocol");
String host = actionRequest.getParameter("host");
int port = Integer.parseInt(actionRequest.getParameter("port"));
int maxThreads = Integer.parseInt(actionRequest.getParameter("maxThreads"));
Integer minThreads = getInteger(actionRequest, "minThreads");
String name = actionRequest.getParameter("name");
// Create and configure the connector
WebConnector connector = PortletManager.createWebConnector(actionRequest, name, protocol, host, port);
connector.setMaxThreads(maxThreads);
// todo: more configurable HTTP/Jetty values
if(connector instanceof JettyWebConnector) {
if(minThreads != null) {
((JettyWebConnector)connector).setMinThreads(minThreads.intValue());
}
}
if(protocol.equals(WebContainer.PROTOCOL_HTTPS)) {
//todo: HTTPS values
}
// Start the connector
try {
((GeronimoManagedBean)connector).startRecursive();
} catch (Exception e) {
log.error("Unable to start connector", e); //todo: get into rendered page somehow?
}
actionResponse.setRenderParameter("mode", "list");
} else if(mode.equals("save")) { // User just submitted the form to update a connector
// Get submitted values
//todo: lots of validation
String host = actionRequest.getParameter("host");
int port = Integer.parseInt(actionRequest.getParameter("port"));
int maxThreads = Integer.parseInt(actionRequest.getParameter("maxThreads"));
Integer minThreads = getInteger(actionRequest, "minThreads");
String objectName = actionRequest.getParameter("objectName");
// Identify and update the connector
WebConnector connector = null;
WebConnector all[] = PortletManager.getWebConnectors(actionRequest);
for (int i = 0; i < all.length; i++) {
WebConnector conn = all[i];
if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) {
connector = conn;
break;
}
}
if(connector != null) {
connector.setHost(host);
connector.setPort(port);
connector.setMaxThreads(maxThreads);
if(connector instanceof JettyWebConnector) {
if(minThreads != null) {
((JettyWebConnector)connector).setMinThreads(minThreads.intValue());
}
}
}
actionResponse.setRenderParameter("mode", "list");
} else if(mode.equals("start")) {
String objectName = actionRequest.getParameter("name");
// work with the current connector to start it.
WebConnector connector = null;
WebConnector all[] = PortletManager.getWebConnectors(actionRequest);
for (int i = 0; i < all.length; i++) {
WebConnector conn = all[i];
if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) {
connector = conn;
break;
}
}
if(connector != null) {
try {
((GeronimoManagedBean)connector).startRecursive();
} catch (Exception e) {
log.error("Unable to start connector", e); //todo: get into rendered page somehow?
}
}
else {
log.error("Incorrect connector reference"); //Replace this with correct error processing
}
actionResponse.setRenderParameter("name", objectName);
actionResponse.setRenderParameter("mode", "list");
} else if(mode.equals("stop")) {
String objectName = actionRequest.getParameter("name");
// work with the current connector to stop it.
WebConnector connector = null;
WebConnector all[] = PortletManager.getWebConnectors(actionRequest);
for (int i = 0; i < all.length; i++) {
WebConnector conn = all[i];
if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) {
connector = conn;
break;
}
}
if(connector != null) {
try {
((GeronimoManagedBean)connector).stop();
} catch (Exception e) {
log.error("Unable to stop connector", e); //todo: get into rendered page somehow?
}
}
else {
log.error("Incorrect connector reference"); //Replace this with correct error processing
}
actionResponse.setRenderParameter("name", objectName);
actionResponse.setRenderParameter("mode", "list");
} else if(mode.equals("edit")) {
String objectName = actionRequest.getParameter("name");
actionResponse.setRenderParameter("objectName", objectName);
actionResponse.setRenderParameter("mode", "edit");
} else if(mode.equals("delete")) { // User chose to delete a connector
String objectName = actionRequest.getParameter("name");
PortletManager.getCurrentWebContainer(actionRequest).removeConnector(objectName);
actionResponse.setRenderParameter("mode", "list");
}
}
public void processAction(ActionRequest actionRequest,
ActionResponse actionResponse) throws PortletException, IOException {
String mode = actionRequest.getParameter("mode");
WebContainer container = PortletManager.getCurrentWebContainer(actionRequest);
String server = "generic";
if(container instanceof JettyContainer) {
server = "jetty";
} else if (container instanceof TomcatContainer) {
server = "tomcat";
}
actionResponse.setRenderParameter("server", server);
if(mode.equals("new")) {
// User selected to add a new connector, need to show criteria portlet
actionResponse.setRenderParameter("mode", "new");
String protocol = actionRequest.getParameter("protocol");
actionResponse.setRenderParameter("protocol", protocol);
} else if(mode.equals("add")) { // User just submitted the form to add a new connector
// Get submitted values
//todo: lots of validation
String protocol = actionRequest.getParameter("protocol");
String host = actionRequest.getParameter("host");
int port = Integer.parseInt(actionRequest.getParameter("port"));
int maxThreads = Integer.parseInt(actionRequest.getParameter("maxThreads"));
Integer minThreads = getInteger(actionRequest, "minThreads");
String name = actionRequest.getParameter("name");
// Create and configure the connector
WebConnector connector = PortletManager.createWebConnector(actionRequest, name, protocol, host, port);
connector.setMaxThreads(maxThreads);
// todo: more configurable HTTP/Jetty values
if(connector instanceof JettyWebConnector) {
if(minThreads != null) {
((JettyWebConnector)connector).setMinThreads(minThreads.intValue());
}
}
if(protocol.equals(WebContainer.PROTOCOL_HTTPS)) {
String keystoreType = actionRequest.getParameter("keystoreType");
String keystoreFile = actionRequest.getParameter("keystoreFile");
String privateKeyPass = actionRequest.getParameter("privateKeyPassword");
String keystorePass = actionRequest.getParameter("keystorePassword");
String secureProtocol = actionRequest.getParameter("secureProtocol");
String algorithm = actionRequest.getParameter("algorithm");
boolean clientAuth = isValid(actionRequest.getParameter("clientAuth"));
SecureConnector secure = (SecureConnector) connector;
if(isValid(keystoreType)) {secure.setKeystoreType(keystoreType);}
if(isValid(keystoreFile)) {secure.setKeystoreFileName(keystoreFile);}
if(isValid(keystorePass)) {secure.setKeystorePassword(keystorePass);}
if(isValid(secureProtocol)) {secure.setSecureProtocol(secureProtocol);}
if(isValid(algorithm)) {secure.setAlgorithm(algorithm);}
secure.setClientAuthRequired(clientAuth);
if(secure instanceof JettySecureConnector) {
if(isValid(privateKeyPass)) {((JettySecureConnector)secure).setKeyPassword(privateKeyPass);}
}
}
// Start the connector
try {
((GeronimoManagedBean)connector).startRecursive();
} catch (Exception e) {
log.error("Unable to start connector", e); //todo: get into rendered page somehow?
}
actionResponse.setRenderParameter("mode", "list");
} else if(mode.equals("save")) { // User just submitted the form to update a connector
// Get submitted values
//todo: lots of validation
String host = actionRequest.getParameter("host");
int port = Integer.parseInt(actionRequest.getParameter("port"));
int maxThreads = Integer.parseInt(actionRequest.getParameter("maxThreads"));
Integer minThreads = getInteger(actionRequest, "minThreads");
String objectName = actionRequest.getParameter("objectName");
// Identify and update the connector
WebConnector connector = null;
WebConnector all[] = PortletManager.getWebConnectors(actionRequest);
for (int i = 0; i < all.length; i++) {
WebConnector conn = all[i];
if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) {
connector = conn;
break;
}
}
if(connector != null) {
connector.setHost(host);
connector.setPort(port);
connector.setMaxThreads(maxThreads);
if(connector instanceof JettyWebConnector) {
if(minThreads != null) {
((JettyWebConnector)connector).setMinThreads(minThreads.intValue());
}
}
if(connector instanceof SecureConnector) {
String keystoreType = actionRequest.getParameter("keystoreType");
String keystoreFile = actionRequest.getParameter("keystoreFile");
String privateKeyPass = actionRequest.getParameter("privateKeyPassword");
String keystorePass = actionRequest.getParameter("keystorePassword");
String secureProtocol = actionRequest.getParameter("secureProtocol");
String algorithm = actionRequest.getParameter("algorithm");
boolean clientAuth = isValid(actionRequest.getParameter("clientAuth"));
SecureConnector secure = (SecureConnector) connector;
if(isValid(keystoreType)) {secure.setKeystoreType(keystoreType);}
if(isValid(keystoreFile)) {secure.setKeystoreFileName(keystoreFile);}
if(isValid(keystorePass)) {secure.setKeystorePassword(keystorePass);}
if(isValid(secureProtocol)) {secure.setSecureProtocol(secureProtocol);}
if(isValid(algorithm)) {secure.setAlgorithm(algorithm);}
secure.setClientAuthRequired(clientAuth);
if(secure instanceof JettySecureConnector) {
if(isValid(privateKeyPass)) {((JettySecureConnector)secure).setKeyPassword(privateKeyPass);}
}
}
}
actionResponse.setRenderParameter("mode", "list");
} else if(mode.equals("start")) {
String objectName = actionRequest.getParameter("name");
// work with the current connector to start it.
WebConnector connector = null;
WebConnector all[] = PortletManager.getWebConnectors(actionRequest);
for (int i = 0; i < all.length; i++) {
WebConnector conn = all[i];
if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) {
connector = conn;
break;
}
}
if(connector != null) {
try {
((GeronimoManagedBean)connector).startRecursive();
} catch (Exception e) {
log.error("Unable to start connector", e); //todo: get into rendered page somehow?
}
}
else {
log.error("Incorrect connector reference"); //Replace this with correct error processing
}
actionResponse.setRenderParameter("name", objectName);
actionResponse.setRenderParameter("mode", "list");
} else if(mode.equals("stop")) {
String objectName = actionRequest.getParameter("name");
// work with the current connector to stop it.
WebConnector connector = null;
WebConnector all[] = PortletManager.getWebConnectors(actionRequest);
for (int i = 0; i < all.length; i++) {
WebConnector conn = all[i];
if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) {
connector = conn;
break;
}
}
if(connector != null) {
try {
((GeronimoManagedBean)connector).stop();
} catch (Exception e) {
log.error("Unable to stop connector", e); //todo: get into rendered page somehow?
}
}
else {
log.error("Incorrect connector reference"); //Replace this with correct error processing
}
actionResponse.setRenderParameter("name", objectName);
actionResponse.setRenderParameter("mode", "list");
} else if(mode.equals("edit")) {
String objectName = actionRequest.getParameter("name");
actionResponse.setRenderParameter("objectName", objectName);
actionResponse.setRenderParameter("mode", "edit");
} else if(mode.equals("delete")) { // User chose to delete a connector
String objectName = actionRequest.getParameter("name");
PortletManager.getCurrentWebContainer(actionRequest).removeConnector(objectName);
actionResponse.setRenderParameter("mode", "list");
}
}
|
applications/console-standard/src/java/org/apache/geronimo/console/webmanager/ConnectorPortlet.java
|
satd-removal_data_31
|
FIXME: Make a static with the default search provider
private void loadSearchProvider( final Properties properties ) {
// See if we're using Lucene, and if so, ensure that its index directory is up to date.
final String providerClassName = TextUtil.getStringProperty( properties, PROP_SEARCHPROVIDER, DEFAULT_SEARCHPROVIDER );
try {
final Class<?> providerClass = ClassUtil.findClass( "org.apache.wiki.search", providerClassName );
m_searchProvider = ( SearchProvider )providerClass.newInstance();
} catch( final ClassNotFoundException | InstantiationException | IllegalAccessException e ) {
log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e);
}
if( null == m_searchProvider ) {
// FIXME: Make a static with the default search provider
m_searchProvider = new BasicSearchProvider();
}
log.debug("Loaded search provider " + m_searchProvider);
}
private void loadSearchProvider( final Properties properties ) {
// See if we're using Lucene, and if so, ensure that its index directory is up-to-date.
final String providerClassName = TextUtil.getStringProperty( properties, PROP_SEARCHPROVIDER, DEFAULT_SEARCHPROVIDER );
try {
m_searchProvider = ClassUtil.buildInstance( "org.apache.wiki.search", providerClassName );
} catch( final ReflectiveOperationException e ) {
log.warn( "Failed loading SearchProvider, will use BasicSearchProvider.", e );
}
if( null == m_searchProvider ) {
m_searchProvider = new BasicSearchProvider();
}
log.debug( "Loaded search provider {}", m_searchProvider );
}
|
jspwiki-main/src/main/java/org/apache/wiki/search/DefaultSearchManager.java
|
satd-removal_data_32
|
todo sync this
@Override
public void processResult(int i, String s, Object o, String s1) {
KeeperException.Code returnCode = KeeperException.Code.get(i);
ZkLocalStatusAndEndpoints statusAndEndpoints = (ZkLocalStatusAndEndpoints) o;
log.info("Claim callback " + returnCode.name() + " " + s);
switch (returnCode) {
case OK:
synchronized (this) {
storage = Storage.DIRTY;
}
try {
// todo sync this
statusAndEndpoints.writeStatusEndpoint();
synchronized (statusAndEndpoints) {
statusAndEndpoints.storage = Storage.SYNCED;
}
} catch (CoordinateMissingException e) {
log.info("Problems writing config, coordinate missing");
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.NOT_OWNER,
"Can not write config: " + returnCode.name() + " " + s);
break;
} catch (CloudnameException e) {
log.info("Problems writing config." + e.getMessage());
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.LOST_CONNECTION_TO_STORAGE,
"Can not write config after claim: " + returnCode.name() + " " + s);
break;
}
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.COORDINATE_OK, "synced on recovery");
break;
case NODEEXISTS:
synchronized (statusAndEndpoints) {
if (statusAndEndpoints.storage == Storage.DIRTY ||
statusAndEndpoints.storage == Storage.SYNCED ) {
break;
}
}
// synchronized (this) {
// storage = Storage.UNCLAIMED;
// }
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.NOT_OWNER,
"Node already exists.");
break;
case NONODE:
// synchronized (this) {
//storage = Storage.UNCLAIMED;
// }
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.NOT_OWNER,
"No node on claiming coordinate: " + returnCode.name() + " " + s);
break;
default:
//synchronized (this) {
// storage = Storage.UNCLAIMED;
//}
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.LOST_CONNECTION_TO_STORAGE,
"Could not reclaim coordinate. Return code: " + returnCode.name() + " " + s);
}
}
@Override
public void processResult(int i, String s, Object o, String s1) {
KeeperException.Code returnCode = KeeperException.Code.get(i);
ZkLocalStatusAndEndpoints statusAndEndpoints = (ZkLocalStatusAndEndpoints) o;
log.info("Claim callback " + returnCode.name() + " " + s);
switch (returnCode) {
case OK:
synchronized (statusAndEndpoints) {
try {
statusAndEndpoints.writeStatusEndpoint();
storage = Storage.SYNCED;
} catch (CoordinateMissingException e) {
log.info("Problems writing config, coordinate missing");
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.NOT_OWNER,
"Can not write config: " + returnCode.name() + " " + s);
break;
} catch (CloudnameException e) {
log.info("Problems writing config." + e.getMessage());
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.LOST_CONNECTION_TO_STORAGE,
"Can not write config after claim: " + returnCode.name() + " " + s);
break;
}
}
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.COORDINATE_OK, "synced on recovery");
break;
case NODEEXISTS:
synchronized (statusAndEndpoints) {
// If everything is fine, this is not a true negative, so ignore it.
if (storage == Storage.SYNCED && claimed) {
break;
}
}
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.NOT_OWNER, "Node already exists.");
break;
case NONODE:
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.NOT_OWNER,
"No node on claiming coordinate: " + returnCode.name() + " " + s);
break;
default:
statusAndEndpoints.updateCoordinateListenersAndTakeAction(
CoordinateListener.Event.LOST_CONNECTION_TO_STORAGE,
"Could not reclaim coordinate. Return code: " + returnCode.name() + " " + s);
}
}
|
cn/src/main/java/org/cloudname/zk/ZkLocalStatusAndEndpoints.java
|
satd-removal_data_33
|
TODO - use type NAMEDRANGE
public void setRefersToFormula(String formulaText) {
XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(workbook);
Ptg[] ptgs;
try {
ptgs = FormulaParser.parse(formulaText, fpb, FormulaType.CELL); // TODO - use type NAMEDRANGE
} catch (RuntimeException e) {
if (e.getClass().getName().startsWith(FormulaParser.class.getName())) {
throw new IllegalArgumentException("Unparsable formula '" + formulaText + "'", e);
}
throw e;
}
ctName.setStringValue(formulaText);
}
public void setRefersToFormula(String formulaText) {
XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(workbook);
try {
Ptg[] ptgs = FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE);
} catch (RuntimeException e) {
if (e.getClass().getName().startsWith(FormulaParser.class.getName())) {
throw new IllegalArgumentException("Unparsable formula '" + formulaText + "'", e);
}
throw e;
}
ctName.setStringValue(formulaText);
}
|
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFName.java
|
satd-removal_data_34
|
TODO add description
private void ingestWork(ContentContainerObject parent, Resource parentResc, Resource childResc)
throws DepositException {
PID childPid = PIDs.get(childResc.getURI());
WorkObject obj;
boolean skip = skipResumed(childResc);
if (skip) {
obj = repository.getWorkObject(childPid);
ingestChildren(obj, childResc);
// Avoid adding primaryObject relation for a resuming deposit if already present
if (!obj.getResource().hasProperty(Cdr.primaryObject)) {
// Set the primary object for this work if one was specified
addPrimaryObject(obj, childResc);
}
} else {
Model model = ModelFactory.createDefaultModel();
Resource workResc = model.getResource(childPid.getRepositoryPath());
populateAIPProperties(childResc, workResc);
// send txid along with uris for the following actions
FedoraTransaction tx = repository.startTransaction();
// TODO add ACLs
try {
obj = repository.createWorkObject(childPid, model);
parent.addMember(obj);
// TODO add description
// Increment the count of objects deposited prior to adding children
addClicks(1);
log.info("Created work object {} for deposit {}", childPid, getDepositPID());
ingestChildren(obj, childResc);
// Set the primary object for this work if one was specified
addPrimaryObject(obj, childResc);
} catch(Exception e) {
tx.cancel(e);
} finally {
tx.close();
}
}
}
private void ingestWork(ContentContainerObject parent, Resource parentResc, Resource childResc)
throws DepositException, IOException {
PID childPid = PIDs.get(childResc.getURI());
WorkObject obj;
boolean skip = skipResumed(childResc);
if (skip) {
obj = repository.getWorkObject(childPid);
ingestChildren(obj, childResc);
// Avoid adding primaryObject relation for a resuming deposit if already present
if (!obj.getResource().hasProperty(Cdr.primaryObject)) {
// Set the primary object for this work if one was specified
addPrimaryObject(obj, childResc);
}
} else {
Model model = ModelFactory.createDefaultModel();
Resource workResc = model.getResource(childPid.getRepositoryPath());
populateAIPProperties(childResc, workResc);
// send txid along with uris for the following actions
FedoraTransaction tx = repository.startTransaction();
// TODO add ACLs
try {
obj = repository.createWorkObject(childPid, model);
parent.addMember(obj);
addDescription(obj);
// Increment the count of objects deposited prior to adding children
addClicks(1);
log.info("Created work object {} for deposit {}", childPid, getDepositPID());
ingestChildren(obj, childResc);
// Set the primary object for this work if one was specified
addPrimaryObject(obj, childResc);
} catch(Exception e) {
tx.cancel(e);
} finally {
tx.close();
}
}
}
|
deposit/src/main/java/edu/unc/lib/deposit/fcrepo4/IngestContentObjectsJob.java
|
satd-removal_data_35
|
TODO(kevinb): why does the source come out as unknown??
public void testInjectInnerClass() throws Exception {
Injector injector = Guice.createInjector();
try {
injector.getInstance(InnerClass.class);
fail();
} catch (Exception expected) {
// TODO(kevinb): why does the source come out as unknown??
assertContains(expected.getMessage(),
"Error at " + InnerClass.class.getName() + ".class(ErrorMessagesTest.java:",
"Injecting into inner classes is not supported.");
}
}
public void testInjectInnerClass() throws Exception {
Injector injector = Guice.createInjector();
try {
injector.getInstance(InnerClass.class);
fail();
} catch (Exception expected) {
assertContains(expected.getMessage(),
"Injecting into inner classes is not supported.",
"at " + InnerClass.class.getName() + ".class(ErrorMessagesTest.java:");
}
}
|
test/com/google/inject/ErrorMessagesTest.java
|
satd-removal_data_36
|
TODO Copy as Image to Clipboard. But not on Linux 64-bit. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=283960
private void makeLocalToolBar() {
IActionBars bars = getViewSite().getActionBars();
IToolBarManager manager = bars.getToolBarManager();
fDrillDownManager.addNavigationActions(manager);
manager.add(new Separator());
manager.add(fActionPinContent);
manager.add(new Separator());
manager.add(fActionLayout);
final IMenuManager menuManager = bars.getMenuManager();
IMenuManager depthMenuManager = new MenuManager(Messages.ZestView_3);
menuManager.add(depthMenuManager);
// Depth Actions
fDepthActions = new Action[6];
for(int i = 0; i < fDepthActions.length; i++) {
fDepthActions[i] = createDepthAction(i, i + 1);
depthMenuManager.add(fDepthActions[i]);
}
// Set depth from prefs
int depth = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DEPTH);
getContentProvider().setDepth(depth);
fDepthActions[depth].setChecked(true);
// Set filter based on Viewpoint
IMenuManager viewpointMenuManager = new MenuManager(Messages.ZestView_5);
menuManager.add(viewpointMenuManager);
// Get viewpoint from prefs
String viewpointID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_VIEWPOINT);
getContentProvider().setViewpointFilter(ViewpointManager.INSTANCE.getViewpoint(viewpointID));
// Viewpoint actions
fViewpointActions = new ArrayList<IAction>();
for(IViewpoint vp : ViewpointManager.INSTANCE.getAllViewpoints()) {
IAction action = createViewpointMenuAction(vp);
fViewpointActions.add(action);
viewpointMenuManager.add(action);
// Set checked
if(vp.getID().equals(viewpointID)) {
action.setChecked(true);
}
}
// Set filter based on Relationship
IMenuManager relationshipMenuManager = new MenuManager(Messages.ZestView_6);
menuManager.add(relationshipMenuManager);
// Get relationship from prefs
String relationshipID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_RELATIONSHIP);
EClass eClass = (EClass)IArchimatePackage.eINSTANCE.getEClassifier(relationshipID);
getContentProvider().setRelationshipFilter(eClass);
// Relationship actions, first the "None" relationship
fRelationshipActions = new ArrayList<IAction>();
IAction action = createRelationshipMenuAction(null);
if(eClass == null) {
action.setChecked(true);
}
fRelationshipActions.add(action);
relationshipMenuManager.add(action);
// Then get all relationships and sort them
ArrayList<EClass> actionList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getRelationsClasses()));
actionList.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
for(EClass rel : actionList) {
action = createRelationshipMenuAction(rel);
fRelationshipActions.add(action);
relationshipMenuManager.add(action);
// Set checked
if(eClass != null && rel.getName().equals(eClass.getName())) {
action.setChecked(true);
}
}
// Orientation
IMenuManager orientationMenuManager = new MenuManager(Messages.ZestView_32);
menuManager.add(orientationMenuManager);
// Direction
fDirectionActions = new Action[3];
fDirectionActions[0] = createOrientationMenuAction(0, Messages.ZestView_33, ZestViewerContentProvider.DIR_BOTH);
orientationMenuManager.add(fDirectionActions[0]);
fDirectionActions[1] = createOrientationMenuAction(1, Messages.ZestView_34, ZestViewerContentProvider.DIR_IN);
orientationMenuManager.add(fDirectionActions[1]);
fDirectionActions[2] = createOrientationMenuAction(2, Messages.ZestView_35, ZestViewerContentProvider.DIR_OUT);
orientationMenuManager.add(fDirectionActions[2]);
// Set direction from prefs
int direction = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DIRECTION);
getContentProvider().setDirection(direction);
fDirectionActions[direction].setChecked(true);
menuManager.add(new Separator());
// TODO Copy as Image to Clipboard. But not on Linux 64-bit. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=283960
if(!(PlatformUtils.isLinux() && PlatformUtils.is64Bit())) {
menuManager.add(fActionCopyImageToClipboard);
}
menuManager.add(fActionExportImageToFile);
}
private void makeLocalToolBar() {
IActionBars bars = getViewSite().getActionBars();
IToolBarManager manager = bars.getToolBarManager();
fDrillDownManager.addNavigationActions(manager);
manager.add(new Separator());
manager.add(fActionPinContent);
manager.add(new Separator());
manager.add(fActionLayout);
final IMenuManager menuManager = bars.getMenuManager();
IMenuManager depthMenuManager = new MenuManager(Messages.ZestView_3);
menuManager.add(depthMenuManager);
// Depth Actions
fDepthActions = new Action[6];
for(int i = 0; i < fDepthActions.length; i++) {
fDepthActions[i] = createDepthAction(i, i + 1);
depthMenuManager.add(fDepthActions[i]);
}
// Set depth from prefs
int depth = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DEPTH);
getContentProvider().setDepth(depth);
fDepthActions[depth].setChecked(true);
// Set filter based on Viewpoint
IMenuManager viewpointMenuManager = new MenuManager(Messages.ZestView_5);
menuManager.add(viewpointMenuManager);
// Get viewpoint from prefs
String viewpointID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_VIEWPOINT);
getContentProvider().setViewpointFilter(ViewpointManager.INSTANCE.getViewpoint(viewpointID));
// Viewpoint actions
fViewpointActions = new ArrayList<IAction>();
for(IViewpoint vp : ViewpointManager.INSTANCE.getAllViewpoints()) {
IAction action = createViewpointMenuAction(vp);
fViewpointActions.add(action);
viewpointMenuManager.add(action);
// Set checked
if(vp.getID().equals(viewpointID)) {
action.setChecked(true);
}
}
// Set filter based on Relationship
IMenuManager relationshipMenuManager = new MenuManager(Messages.ZestView_6);
menuManager.add(relationshipMenuManager);
// Get relationship from prefs
String relationshipID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_RELATIONSHIP);
EClass eClass = (EClass)IArchimatePackage.eINSTANCE.getEClassifier(relationshipID);
getContentProvider().setRelationshipFilter(eClass);
// Relationship actions, first the "None" relationship
fRelationshipActions = new ArrayList<IAction>();
IAction action = createRelationshipMenuAction(null);
if(eClass == null) {
action.setChecked(true);
}
fRelationshipActions.add(action);
relationshipMenuManager.add(action);
// Then get all relationships and sort them
ArrayList<EClass> actionList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getRelationsClasses()));
actionList.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
for(EClass rel : actionList) {
action = createRelationshipMenuAction(rel);
fRelationshipActions.add(action);
relationshipMenuManager.add(action);
// Set checked
if(eClass != null && rel.getName().equals(eClass.getName())) {
action.setChecked(true);
}
}
// Orientation
IMenuManager orientationMenuManager = new MenuManager(Messages.ZestView_32);
menuManager.add(orientationMenuManager);
// Direction
fDirectionActions = new Action[3];
fDirectionActions[0] = createOrientationMenuAction(0, Messages.ZestView_33, ZestViewerContentProvider.DIR_BOTH);
orientationMenuManager.add(fDirectionActions[0]);
fDirectionActions[1] = createOrientationMenuAction(1, Messages.ZestView_34, ZestViewerContentProvider.DIR_IN);
orientationMenuManager.add(fDirectionActions[1]);
fDirectionActions[2] = createOrientationMenuAction(2, Messages.ZestView_35, ZestViewerContentProvider.DIR_OUT);
orientationMenuManager.add(fDirectionActions[2]);
// Set direction from prefs
int direction = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DIRECTION);
getContentProvider().setDirection(direction);
fDirectionActions[direction].setChecked(true);
menuManager.add(new Separator());
menuManager.add(fActionCopyImageToClipboard);
menuManager.add(fActionExportImageToFile);
}
|
com.archimatetool.zest/src/com/archimatetool/zest/ZestView.java
|
satd-removal_data_37
|
XXX lang is not checked??
private void walk(Node n, Parse parse, HTMLMetaTags metaTags, String base, List outlinks) {
if (n instanceof Element) {
String name = n.getNodeName();
if (name.equalsIgnoreCase("script")) {
String lang = null;
Node lNode = n.getAttributes().getNamedItem("language");
if (lNode == null) lang = "javascript";
else lang = lNode.getNodeValue();
//XXX lang is not checked??
StringBuffer script = new StringBuffer();
NodeList nn = n.getChildNodes();
if (nn.getLength() > 0) {
for (int i = 0; i < nn.getLength(); i++) {
if (i > 0) script.append('\n');
script.append(nn.item(i).getNodeValue());
}
if (LOG.isDebugEnabled()) {
LOG.info("script: language=" + lang + ", text: " + script.toString());
}
Outlink[] links = getJSLinks(script.toString(), "", base);
if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links));
// no other children of interest here, go one level up.
return;
}
} else {
// process all HTML 4.0 events, if present...
NamedNodeMap attrs = n.getAttributes();
int len = attrs.getLength();
for (int i = 0; i < len; i++) {
// Window: onload,onunload
// Form: onchange,onsubmit,onreset,onselect,onblur,onfocus
// Keyboard: onkeydown,onkeypress,onkeyup
// Mouse: onclick,ondbclick,onmousedown,onmouseout,onmousover,onmouseup
Node anode = attrs.item(i);
Outlink[] links = null;
if (anode.getNodeName().startsWith("on")) {
links = getJSLinks(anode.getNodeValue(), "", base);
} else if (anode.getNodeName().equalsIgnoreCase("href")) {
String val = anode.getNodeValue();
if (val != null && val.toLowerCase().indexOf("javascript:") != -1) {
links = getJSLinks(val, "", base);
}
}
if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links));
}
}
}
NodeList nl = n.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
walk(nl.item(i), parse, metaTags, base, outlinks);
}
}
private void walk(Node n, Parse parse, HTMLMetaTags metaTags, String base, List outlinks) {
if (n instanceof Element) {
String name = n.getNodeName();
if (name.equalsIgnoreCase("script")) {
String lang = null;
Node lNode = n.getAttributes().getNamedItem("language");
if (lNode == null) lang = "javascript";
else lang = lNode.getNodeValue();
StringBuffer script = new StringBuffer();
NodeList nn = n.getChildNodes();
if (nn.getLength() > 0) {
for (int i = 0; i < nn.getLength(); i++) {
if (i > 0) script.append('\n');
script.append(nn.item(i).getNodeValue());
}
// if (LOG.isInfoEnabled()) {
// LOG.info("script: language=" + lang + ", text: " + script.toString());
// }
Outlink[] links = getJSLinks(script.toString(), "", base);
if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links));
// no other children of interest here, go one level up.
return;
}
} else {
// process all HTML 4.0 events, if present...
NamedNodeMap attrs = n.getAttributes();
int len = attrs.getLength();
for (int i = 0; i < len; i++) {
// Window: onload,onunload
// Form: onchange,onsubmit,onreset,onselect,onblur,onfocus
// Keyboard: onkeydown,onkeypress,onkeyup
// Mouse: onclick,ondbclick,onmousedown,onmouseout,onmousover,onmouseup
Node anode = attrs.item(i);
Outlink[] links = null;
if (anode.getNodeName().startsWith("on")) {
links = getJSLinks(anode.getNodeValue(), "", base);
} else if (anode.getNodeName().equalsIgnoreCase("href")) {
String val = anode.getNodeValue();
if (val != null && val.toLowerCase().indexOf("javascript:") != -1) {
links = getJSLinks(val, "", base);
}
}
if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links));
}
}
}
NodeList nl = n.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
walk(nl.item(i), parse, metaTags, base, outlinks);
}
}
|
src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
|
satd-removal_data_38
|
TODO: implement this!
public void removeUserFromGroup(A_CmsUser currentUser, A_CmsProject currentProject,
String username, String groupname)
throws CmsException {
// TODO: implement this!
return ;
}
public void removeUserFromGroup(A_CmsUser currentUser, A_CmsProject currentProject,
String username, String groupname)
throws CmsException {
// Check the security
if( isAdmin(currentUser, currentProject) ) {
m_userRb.removeUserFromGroup(username, groupname);
} else {
throw new CmsException(CmsException.C_EXTXT[CmsException.C_NO_ACCESS],
CmsException.C_NO_ACCESS);
}
}
|
src/com/opencms/file/CmsResourceBroker.java
|
satd-removal_data_39
|
TODO what about placeholder for null? should be in searchresult (transient field?)
@Override
public void writeTo(SearchResponse searchResponse, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
final CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(entityStream));
final ImmutableSortedSet<String> sortedFields = ImmutableSortedSet.copyOf(searchResponse.fields);
// write field headers
csvWriter.writeNext(sortedFields.toArray(new String[sortedFields.size()]));
// write result set in same order as the header row
final String[] fieldValues = new String[sortedFields.size()];
for (ResultMessage message : searchResponse.messages) {
int idx = 0;
// first collect all values from the current message
for (String fieldName : sortedFields) {
final Object val = message.message.get(fieldName);
fieldValues[idx++] = firstNonNull(val, "").toString(); // TODO what about placeholder for null? should be in searchresult (transient field?)
}
// write the complete line, some fields might not be present in the message, so there might be null values
csvWriter.writeNext(fieldValues);
}
if (csvWriter.checkError()) {
log.error("Encountered unspecified error when writing message result as CSV, result is likely malformed.");
}
csvWriter.close();
}
@Override
public void writeTo(SearchResponse searchResponse, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
final CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(entityStream));
final ImmutableSortedSet<String> sortedFields = ImmutableSortedSet.copyOf(searchResponse.fields);
// write field headers
csvWriter.writeNext(sortedFields.toArray(new String[sortedFields.size()]));
// write result set in same order as the header row
final String[] fieldValues = new String[sortedFields.size()];
for (ResultMessage message : searchResponse.messages) {
int idx = 0;
// first collect all values from the current message
for (String fieldName : sortedFields) {
final Object val = message.message.get(fieldName);
fieldValues[idx++] = ((val == null) ? null : val.toString());
}
// write the complete line, some fields might not be present in the message, so there might be null values
csvWriter.writeNext(fieldValues);
}
if (csvWriter.checkError()) {
log.error("Encountered unspecified error when writing message result as CSV, result is likely malformed.");
}
csvWriter.close();
}
|
graylog2-server/src/main/java/org/graylog2/rest/resources/search/responses/SearchResponseCsvWriter.java
|
satd-removal_data_40
|
TODO: multicast properties
@Override
public void execute(final AsyncCallback<List<SocketBinding>> callback) {
// /socket-binding-group=standard-sockets:read-resource(recursive=true)
ModelNode operation = new ModelNode();
operation.get(ADDRESS).add("socket-binding-group", groupName);
operation.get(OP).set(READ_RESOURCE_OPERATION);
operation.get(RECURSIVE).set(true);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = ModelNode.fromBase64(result.getResponseText());
ModelNode payload = response.get("result").asObject();
List<ModelNode> socketDescriptions= payload.get("socket-binding").asList();
List<SocketBinding> bindings = new ArrayList<SocketBinding>();
for(ModelNode socket : socketDescriptions)
{
ModelNode value = socket.asProperty().getValue();
SocketBinding sb = factory.socketBinding().as();
sb.setName(value.get("name").asString());
sb.setGroup(groupName);
sb.setPort(value.get("port").asInt());
String interfaceValue = value.get("interface").isDefined() ?
value.get("interface").asString() : "not set";
sb.setInterface(interfaceValue);
// TODO: multicast properties
sb.setMultiCastAddress("not set");
sb.setMultiCastPort(-1);
bindings.add(sb);
}
callback.onSuccess(bindings);
}
});
}
@Override
public void execute(final AsyncCallback<List<SocketBinding>> callback) {
// /socket-binding-group=standard-sockets:read-resource(recursive=true)
ModelNode operation = new ModelNode();
operation.get(ADDRESS).add("socket-binding-group", groupName);
operation.get(OP).set(READ_RESOURCE_OPERATION);
operation.get(RECURSIVE).set(true);
dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = ModelNode.fromBase64(result.getResponseText());
ModelNode payload = response.get("result").asObject();
List<ModelNode> socketDescriptions= payload.get("socket-binding").asList();
List<SocketBinding> bindings = new ArrayList<SocketBinding>();
for(ModelNode socket : socketDescriptions)
{
ModelNode value = socket.asProperty().getValue();
SocketBinding sb = factory.socketBinding().as();
sb.setName(value.get("name").asString());
sb.setGroup(groupName);
sb.setPort(value.get("port").asInt());
String interfaceValue = value.get("interface").isDefined() ?
value.get("interface").asString() : "not set";
sb.setInterface(interfaceValue);
if(value.hasDefined("multicast-port"))
{
sb.setMultiCastAddress(value.get("multicast-address").asString());
sb.setMultiCastPort(value.get("multicast-port").asInt());
}
else
{
sb.setMultiCastAddress("");
sb.setMultiCastPort(0);
}
bindings.add(sb);
}
callback.onSuccess(bindings);
}
});
}
|
gui/src/main/java/org/jboss/as/console/client/shared/general/model/LoadSocketBindingsCmd.java
|
satd-removal_data_41
|
todo log message
public void handleEvent(final ConnectedMessageChannel channel) {
final Pooled<ByteBuffer> pooledBuffer = connection.allocate();
try {
final ByteBuffer buffer = pooledBuffer.getResource();
final int res;
try {
res = channel.receive(buffer);
} catch (IOException e) {
connection.handleException(e);
return;
}
if (res == 0) {
return;
}
if (res == -1) {
connection.handleException(client.abruptClose(connection));
return;
}
buffer.flip();
final byte msgType = buffer.get();
switch (msgType) {
case Protocol.CONNECTION_ALIVE: {
client.trace("Client received connection alive");
connection.sendAliveResponse();
return;
}
case Protocol.CONNECTION_ALIVE_ACK: {
client.trace("Client received connection alive ack");
return;
}
case Protocol.CONNECTION_CLOSE: {
client.trace("Client received connection close request");
connection.handlePreAuthCloseRequest();
return;
}
case Protocol.AUTH_CHALLENGE: {
client.trace("Client received authentication challenge");
connection.getChannel().suspendReads();
connection.getExecutor().execute(new Runnable() {
public void run() {
final boolean clientComplete = saslClient.isComplete();
if (clientComplete) {
connection.handleException(new SaslException("Received extra auth message after completion"));
return;
}
final byte[] response;
final byte[] challenge = Buffers.take(buffer, buffer.remaining());
try {
response = saslClient.evaluateChallenge(challenge);
if (msgType == Protocol.AUTH_COMPLETE && response != null && response.length > 0) {
connection.handleException(new SaslException("Received extra auth message after completion"));
return;
}
} catch (Exception e) {
client.tracef("Client authentication failed: %s", e);
failedMechs.add(saslClient.getMechanismName());
sendCapRequest(serverName);
return;
}
client.trace("Client sending authentication response");
final Pooled<ByteBuffer> pooled = connection.allocate();
final ByteBuffer sendBuffer = pooled.getResource();
sendBuffer.put(Protocol.AUTH_RESPONSE);
sendBuffer.put(response);
sendBuffer.flip();
connection.send(pooled);
connection.getChannel().resumeReads();
return;
}
});
return;
}
case Protocol.AUTH_COMPLETE: {
client.trace("Client received authentication complete");
connection.getChannel().suspendReads();
connection.getExecutor().execute(new Runnable() {
public void run() {
final boolean clientComplete = saslClient.isComplete();
final byte[] challenge = Buffers.take(buffer, buffer.remaining());
if (!clientComplete) try {
final byte[] response = saslClient.evaluateChallenge(challenge);
if (response != null && response.length > 0) {
connection.handleException(new SaslException("Received extra auth message after completion"));
return;
}
if (!saslClient.isComplete()) {
connection.handleException(new SaslException("Client not complete after processing auth complete message"));
return;
}
} catch (SaslException e) {
// todo log message
failedMechs.add(saslClient.getMechanismName());
sendCapRequest(serverName);
return;
}
final Object qop = saslClient.getNegotiatedProperty(Sasl.QOP);
if ("auth-int".equals(qop) || "auth-conf".equals(qop)) {
connection.setSaslWrapper(SaslWrapper.create(saslClient));
}
// auth complete.
final ConnectionHandlerFactory connectionHandlerFactory = new ConnectionHandlerFactory() {
public ConnectionHandler createInstance(final ConnectionHandlerContext connectionContext) {
// this happens immediately.
final RemoteConnectionHandler connectionHandler = new RemoteConnectionHandler(connectionContext, connection, authorizationID, remoteEndpointName);
connection.setReadListener(new RemoteReadListener(connectionHandler, connection));
return connectionHandler;
}
};
connection.getResult().setResult(connectionHandlerFactory);
connection.getChannel().resumeReads();
return;
}
});
return;
}
case Protocol.AUTH_REJECTED: {
client.trace("Client received authentication rejected");
failedMechs.add(saslClient.getMechanismName());
sendCapRequest(serverName);
return;
}
default: {
client.unknownProtocolId(msgType);
connection.handleException(client.invalidMessage(connection));
return;
}
}
} finally {
pooledBuffer.free();
}
}
public void handleEvent(final ConnectedMessageChannel channel) {
final Pooled<ByteBuffer> pooledBuffer = connection.allocate();
try {
final ByteBuffer buffer = pooledBuffer.getResource();
final int res;
try {
res = channel.receive(buffer);
} catch (IOException e) {
connection.handleException(e);
return;
}
if (res == 0) {
return;
}
if (res == -1) {
connection.handleException(client.abruptClose(connection));
return;
}
buffer.flip();
final byte msgType = buffer.get();
switch (msgType) {
case Protocol.CONNECTION_ALIVE: {
client.trace("Client received connection alive");
connection.sendAliveResponse();
return;
}
case Protocol.CONNECTION_ALIVE_ACK: {
client.trace("Client received connection alive ack");
return;
}
case Protocol.CONNECTION_CLOSE: {
client.trace("Client received connection close request");
connection.handlePreAuthCloseRequest();
return;
}
case Protocol.AUTH_CHALLENGE: {
client.trace("Client received authentication challenge");
connection.getChannel().suspendReads();
connection.getExecutor().execute(new Runnable() {
public void run() {
final boolean clientComplete = saslClient.isComplete();
if (clientComplete) {
connection.handleException(new SaslException("Received extra auth message after completion"));
return;
}
final byte[] response;
final byte[] challenge = Buffers.take(buffer, buffer.remaining());
try {
response = saslClient.evaluateChallenge(challenge);
if (msgType == Protocol.AUTH_COMPLETE && response != null && response.length > 0) {
connection.handleException(new SaslException("Received extra auth message after completion"));
return;
}
} catch (Throwable e) {
final String mechanismName = saslClient.getMechanismName();
client.debugf("Client authentication failed for mechanism %s: %s", mechanismName, e);
failedMechs.add(mechanismName);
sendCapRequest(serverName);
connection.getChannel().resumeReads();
return;
}
client.trace("Client sending authentication response");
final Pooled<ByteBuffer> pooled = connection.allocate();
final ByteBuffer sendBuffer = pooled.getResource();
sendBuffer.put(Protocol.AUTH_RESPONSE);
sendBuffer.put(response);
sendBuffer.flip();
connection.send(pooled);
connection.getChannel().resumeReads();
return;
}
});
return;
}
case Protocol.AUTH_COMPLETE: {
client.trace("Client received authentication complete");
connection.getChannel().suspendReads();
connection.getExecutor().execute(new Runnable() {
public void run() {
final boolean clientComplete = saslClient.isComplete();
final byte[] challenge = Buffers.take(buffer, buffer.remaining());
if (!clientComplete) try {
final byte[] response = saslClient.evaluateChallenge(challenge);
if (response != null && response.length > 0) {
connection.handleException(new SaslException("Received extra auth message after completion"));
return;
}
if (!saslClient.isComplete()) {
connection.handleException(new SaslException("Client not complete after processing auth complete message"));
return;
}
} catch (Throwable e) {
final String mechanismName = saslClient.getMechanismName();
client.debugf("Client authentication failed for mechanism %s: %s", mechanismName, e);
failedMechs.add(mechanismName);
sendCapRequest(serverName);
return;
}
final Object qop = saslClient.getNegotiatedProperty(Sasl.QOP);
if ("auth-int".equals(qop) || "auth-conf".equals(qop)) {
connection.setSaslWrapper(SaslWrapper.create(saslClient));
}
// auth complete.
final ConnectionHandlerFactory connectionHandlerFactory = new ConnectionHandlerFactory() {
public ConnectionHandler createInstance(final ConnectionHandlerContext connectionContext) {
// this happens immediately.
final RemoteConnectionHandler connectionHandler = new RemoteConnectionHandler(connectionContext, connection, authorizationID, remoteEndpointName);
connection.setReadListener(new RemoteReadListener(connectionHandler, connection));
return connectionHandler;
}
};
connection.getResult().setResult(connectionHandlerFactory);
connection.getChannel().resumeReads();
return;
}
});
return;
}
case Protocol.AUTH_REJECTED: {
final String mechanismName = saslClient.getMechanismName();
client.debugf("Client received authentication rejected for mechanism %s", mechanismName);
failedMechs.add(mechanismName);
sendCapRequest(serverName);
return;
}
default: {
client.unknownProtocolId(msgType);
connection.handleException(client.invalidMessage(connection));
return;
}
}
} finally {
pooledBuffer.free();
}
}
|
src/main/java/org/jboss/remoting3/remote/ClientConnectionOpenListener.java
|
satd-removal_data_42
|
TODO: Support exchange headers for wait and timeout values, see Exchange constants
public void process(final Exchange exchange) throws Exception {
final Processor output = getProcessor();
if (output == null) {
// no output then return
return;
}
// use a new copy of the exchange to route async
final Exchange copy = exchange.newCopy();
// let it execute async and return the Future
Callable<Exchange> task = new Callable<Exchange>() {
public Exchange call() throws Exception {
// must use a copy of the original exchange for processing async
output.process(copy);
return copy;
}
};
// sumbit the task
Future<Exchange> future = getExecutorService().submit(task);
// TODO: Support exchange headers for wait and timeout values, see Exchange constants
if (waitTaskComplete) {
// wait for task to complete
Exchange response = future.get();
// if we are out capable then set the response on the original exchange
if (ExchangeHelper.isOutCapable(exchange)) {
ExchangeHelper.copyResults(exchange, response);
}
} else {
// no we do not expect a reply so lets continue, set a handle to the future task
// in case end user need it later
exchange.getOut().setBody(future);
}
}
public void process(final Exchange exchange) throws Exception {
final Processor output = getProcessor();
if (output == null) {
// no output then return
return;
}
// use a new copy of the exchange to route async
final Exchange copy = exchange.newCopy();
// let it execute async and return the Future
Callable<Exchange> task = new Callable<Exchange>() {
public Exchange call() throws Exception {
// must use a copy of the original exchange for processing async
output.process(copy);
return copy;
}
};
// sumbit the task
Future<Exchange> future = getExecutorService().submit(task);
// compute if we should wait for task to complete or not
boolean wait = waitTaskComplete;
if (exchange.getIn().getHeader(Exchange.ASYNC_WAIT) != null) {
wait = exchange.getIn().getHeader(Exchange.ASYNC_WAIT, Boolean.class);
}
if (wait) {
// wait for task to complete
Exchange response = future.get();
ExchangeHelper.copyResults(exchange, response);
} else {
// no we do not expect a reply so lets continue, set a handle to the future task
// in case end user need it later
exchange.getOut().setBody(future);
}
}
|
camel-core/src/main/java/org/apache/camel/processor/AsyncProcessor.java
|
satd-removal_data_43
|
TODO: Implement remove
@Override
public void remove(IdentityType value) throws IdentityManagementException {
//TODO: Implement remove
}
@Override
public void remove(IdentityType value) throws IdentityManagementException {
storeSelector.getStoreForIdentityOperation(this, IdentityStore.class, IdentityType.class, IdentityOperation.delete)
.remove(this, value);
}
|
modules/idm/impl/src/main/java/org/picketlink/idm/internal/ContextualIdentityManager.java
|
satd-removal_data_44
|
TODO Add an error and a log
public static void saveProjects()
{
ProjectsHandler projectsHandler = Activator.getDefault().getProjectsHandler();
File projectsFile = getProjectsFile();
try
{
BufferedWriter buffWriter = new BufferedWriter( new FileWriter( projectsFile ) );
buffWriter.write( ProjectsExporter.toXml( projectsHandler.getProjects().toArray( new Project[0] ) ) );
buffWriter.close();
}
catch ( IOException e )
{
// TODO Add an error and a log
}
}
public static void saveProjects()
{
ProjectsHandler projectsHandler = Activator.getDefault().getProjectsHandler();
File projectsFile = getProjectsFile();
try
{
BufferedWriter buffWriter = new BufferedWriter( new FileWriter( projectsFile ) );
buffWriter.write( ProjectsExporter.toXml( projectsHandler.getProjects().toArray( new Project[0] ) ) );
buffWriter.close();
}
catch ( IOException e )
{
PluginUtils.logError( "An error occured when saving the projects.", e );
ViewUtils.displayErrorMessageBox( "Projects Saving Error", "An error occured when saving the projects." );
}
}
|
studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/PluginUtils.java
|
satd-removal_data_45
|
TODO should we do time out check between each object call?
@Override
public void initializeObjects(EntityInfo[] entityInfos,
Criteria criteria,
Class<?> entityType,
SearchFactoryImplementor searchFactoryImplementor,
TimeoutManager timeoutManager,
Session session) {
boolean traceEnabled = log.isTraceEnabled();
//Do not call isTimeOut here as the caller might be the last biggie on the list.
final int maxResults = entityInfos.length;
if ( maxResults == 0 ) {
if ( traceEnabled ) {
log.tracef( "No object to initialize", maxResults );
}
return;
}
//TODO should we do time out check between each object call?
for ( EntityInfo entityInfo : entityInfos ) {
ObjectLoaderHelper.load( entityInfo, session );
}
if ( traceEnabled ) {
log.tracef( "Initialized %d objects by lookup method.", maxResults );
}
}
@Override
public void initializeObjects(EntityInfo[] entityInfos, LinkedHashMap<EntityInfoLoadKey, Object> idToObjectMap, ObjectInitializationContext objectInitializationContext) {
boolean traceEnabled = log.isTraceEnabled();
// Do not call isTimeOut here as the caller might be the last biggie on the list.
final int maxResults = entityInfos.length;
if ( maxResults == 0 ) {
if ( traceEnabled ) {
log.tracef( "No object to initialize", maxResults );
}
return;
}
for ( EntityInfo entityInfo : entityInfos ) {
Object o = ObjectLoaderHelper.load( entityInfo, objectInitializationContext.getSession() );
if ( o != null ) {
EntityInfoLoadKey key = new EntityInfoLoadKey( entityInfo.getClazz(), entityInfo.getId() );
idToObjectMap.put( key, o );
}
}
if ( traceEnabled ) {
log.tracef( "Initialized %d objects by lookup method.", maxResults );
}
}
|
orm/src/main/java/org/hibernate/search/query/hibernate/impl/LookupObjectInitializer.java
|
satd-removal_data_46
|
TODO: Do we really need to display this twice? Not like there are any associated stats.
@Override
protected void statsDisplay() {
if (canTreasureHunt) {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.Rank", new Object[] { lootTier }));
}
if (canMagicHunt) {
player.sendMessage(LocaleLoader.getString("Fishing.Enchant.Chance", new Object[] { magicChance }));
}
if (canShake) {
//TODO: Do we really need to display this twice? Not like there are any associated stats.
if (skillValue < 150) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", new Object[] { LocaleLoader.getString("Fishing.Ability.Locked.0") }));
}
else {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.Shake"));
}
}
}
@Override
protected void statsDisplay() {
if (canTreasureHunt) {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.Rank", new Object[] { lootTier }));
}
if (canMagicHunt) {
player.sendMessage(LocaleLoader.getString("Fishing.Enchant.Chance", new Object[] { magicChance }));
}
if (canShake) {
if (skillValue < 150) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", new Object[] { LocaleLoader.getString("Fishing.Ability.Locked.0") }));
}
else {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.Shake", new Object[] { shakeChance }));
}
}
}
|
src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java
|
satd-removal_data_47
|
TODO: TL this.
@Override
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
final ItemStack stack = ess.getItemDb().get(args[1]);
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (sender instanceof Player
&& (ess.getSettings().permissionBasedItemSpawn()
? (!ess.getUser(sender).isAuthorized("essentials.give.item-all")
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + itemname)
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + stack.getTypeId()))
: (!ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt")
&& !ess.getUser(sender).canSpawnItem(stack.getTypeId()))))
{
throw new Exception(_("cantSpawnItem", itemname));
}
final User giveTo = getPlayer(server, args, 0);
if (args.length > 3 && Util.isInt(args[2]) && Util.isInt(args[3]))
{
stack.setAmount(Integer.parseInt(args[2]));
stack.setDurability(Short.parseShort(args[3]));
}
else if (args.length > 2 && Integer.parseInt(args[2]) > 0)
{
stack.setAmount(Integer.parseInt(args[2]));
}
else if (ess.getSettings().getDefaultStackSize() > 0)
{
stack.setAmount(ess.getSettings().getDefaultStackSize());
}
else if (ess.getSettings().getOversizedStackSize() > 0 && giveTo.isAuthorized("essentials.oversizedstacks"))
{
stack.setAmount(ess.getSettings().getOversizedStackSize());
}
if (args.length > 3)
{
for (int i = Util.isInt(args[3]) ? 4 : 3; i < args.length; i++)
{
final String[] split = args[i].split("[:+',;.]", 2);
if (split.length < 1)
{
continue;
}
final Enchantment enchantment = Commandenchant.getEnchantment(split[0], sender instanceof Player ? ess.getUser(sender) : null);
int level;
if (split.length > 1)
{
level = Integer.parseInt(split[1]);
}
else
{
level = enchantment.getMaxLevel();
}
stack.addEnchantment(enchantment, level);
}
}
if (stack.getType() == Material.AIR)
{
throw new Exception(_("cantSpawnItem", "Air"));
}
//TODO: TL this.
final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ');
sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + ".");
if (giveTo.isAuthorized("essentials.oversizedstacks"))
{
InventoryWorkaround.addItem(giveTo.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack);
}
else
{
InventoryWorkaround.addItem(giveTo.getInventory(), true, stack);
}
giveTo.updateInventory();
}
@Override
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
final ItemStack stack = ess.getItemDb().get(args[1]);
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (sender instanceof Player
&& (ess.getSettings().permissionBasedItemSpawn()
? (!ess.getUser(sender).isAuthorized("essentials.give.item-all")
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + itemname)
&& !ess.getUser(sender).isAuthorized("essentials.give.item-" + stack.getTypeId()))
: (!ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt")
&& !ess.getUser(sender).canSpawnItem(stack.getTypeId()))))
{
throw new Exception(_("cantSpawnItem", itemname));
}
final User giveTo = getPlayer(server, args, 0);
if (args.length > 3 && Util.isInt(args[2]) && Util.isInt(args[3]))
{
stack.setAmount(Integer.parseInt(args[2]));
stack.setDurability(Short.parseShort(args[3]));
}
else if (args.length > 2 && Integer.parseInt(args[2]) > 0)
{
stack.setAmount(Integer.parseInt(args[2]));
}
else if (ess.getSettings().getDefaultStackSize() > 0)
{
stack.setAmount(ess.getSettings().getDefaultStackSize());
}
else if (ess.getSettings().getOversizedStackSize() > 0 && giveTo.isAuthorized("essentials.oversizedstacks"))
{
stack.setAmount(ess.getSettings().getOversizedStackSize());
}
if (args.length > 3)
{
for (int i = Util.isInt(args[3]) ? 4 : 3; i < args.length; i++)
{
final String[] split = args[i].split("[:+',;.]", 2);
if (split.length < 1)
{
continue;
}
final Enchantment enchantment = Commandenchant.getEnchantment(split[0], sender instanceof Player ? ess.getUser(sender) : null);
int level;
if (split.length > 1)
{
level = Integer.parseInt(split[1]);
}
else
{
level = enchantment.getMaxLevel();
}
stack.addEnchantment(enchantment, level);
}
}
if (stack.getType() == Material.AIR)
{
throw new Exception(_("cantSpawnItem", "Air"));
}
final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ');
sender.sendMessage(_("giveSpawn", stack.getAmount(), itemName, giveTo.getDisplayName()));
if (giveTo.isAuthorized("essentials.oversizedstacks"))
{
InventoryWorkaround.addItem(giveTo.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack);
}
else
{
InventoryWorkaround.addItem(giveTo.getInventory(), true, stack);
}
giveTo.updateInventory();
}
|
Essentials/src/com/earth2me/essentials/commands/Commandgive.java
|
satd-removal_data_48
|
todo - use config to construct a BinningGrid instance of the correct type
@Override
public void setConf(Configuration conf) {
this.conf = conf;
// todo - use config to construct a BinningGrid instance of the correct type
int numRows = conf.getInt(L3Tool.CONFNAME_L3_NUM_ROWS, -1);
binningGrid = new IsinBinningGrid(numRows);
}
@Override
public void setConf(Configuration conf) {
this.conf = conf;
this.binningGrid = L3Config.getBinningGrid(conf);
}
|
calvalus-experiments/src/main/java/com/bc/calvalus/b3/job/L3Partitioner.java
|
satd-removal_data_49
|
TODO: it's confusing that request has fields that get populated but not accepted as input (eg, groupId)
public void execute()
throws MojoExecutionException, MojoFailureException
{
Properties executionProperties = session.getExecutionProperties();
ArchetypeGenerationRequest request = new ArchetypeGenerationRequest()
.setArchetypeGroupId( archetypeGroupId )
.setArchetypeArtifactId( archetypeArtifactId )
.setArchetypeVersion( archetypeVersion )
.setOutputDirectory( basedir.getAbsolutePath() )
.setLocalRepository( localRepository )
.setArchetypeRepository(archetypeRepository)
.setRemoteArtifactRepositories(remoteArtifactRepositories);
try
{
if( interactiveMode.booleanValue() )
{
getLog().info( "Generating project in Interactive mode" );
}
else
{
getLog().info( "Generating project in Batch mode" );
}
selector.selectArchetype( request, interactiveMode, archetypeCatalog );
// TODO: it's confusing that request has fields that get populated but not accepted as input (eg, groupId)
configurator.configureArchetype( request, interactiveMode, executionProperties );
ArchetypeGenerationResult generationResult =
archetype.generateProjectFromArchetype( request );
if( generationResult.getCause() != null )
{
throw new MojoFailureException(
generationResult.getCause(),
generationResult.getCause().getMessage(),
generationResult.getCause().getMessage()
);
}
}
catch ( MojoFailureException ex )
{
throw ex;
}
catch ( Exception ex )
{
throw new MojoFailureException( ex, ex.getMessage(), ex.getMessage() );
}
String artifactId = request.getArtifactId();
String postArchetypeGenerationGoals = request.getArchetypeGoals();
if ( StringUtils.isEmpty( postArchetypeGenerationGoals ) )
{
postArchetypeGenerationGoals = goals;
}
if ( StringUtils.isNotEmpty( postArchetypeGenerationGoals ) )
{
invokePostArchetypeGenerationGoals( postArchetypeGenerationGoals, artifactId );
}
}
public void execute()
throws MojoExecutionException, MojoFailureException
{
Properties executionProperties = session.getExecutionProperties();
ArchetypeGenerationRequest request = new ArchetypeGenerationRequest()
.setArchetypeGroupId( archetypeGroupId )
.setArchetypeArtifactId( archetypeArtifactId )
.setArchetypeVersion( archetypeVersion )
.setOutputDirectory( basedir.getAbsolutePath() )
.setLocalRepository( localRepository )
.setArchetypeRepository(archetypeRepository)
.setRemoteArtifactRepositories(remoteArtifactRepositories);
try
{
if( interactiveMode.booleanValue() )
{
getLog().info( "Generating project in Interactive mode" );
}
else
{
getLog().info( "Generating project in Batch mode" );
}
selector.selectArchetype( request, interactiveMode, archetypeCatalog );
configurator.configureArchetype( request, interactiveMode, executionProperties );
ArchetypeGenerationResult generationResult =
archetype.generateProjectFromArchetype( request );
if( generationResult.getCause() != null )
{
throw new MojoFailureException(
generationResult.getCause(),
generationResult.getCause().getMessage(),
generationResult.getCause().getMessage()
);
}
}
catch ( MojoFailureException ex )
{
throw ex;
}
catch ( Exception ex )
{
throw new MojoFailureException( ex.getMessage() );
}
String artifactId = request.getArtifactId();
String postArchetypeGenerationGoals = request.getArchetypeGoals();
if ( StringUtils.isEmpty( postArchetypeGenerationGoals ) )
{
postArchetypeGenerationGoals = goals;
}
if ( StringUtils.isNotEmpty( postArchetypeGenerationGoals ) )
{
invokePostArchetypeGenerationGoals( postArchetypeGenerationGoals, artifactId );
}
}
|
archetype-plugin/src/main/java/org/apache/maven/archetype/mojos/CreateProjectFromArchetypeMojo.java
|
satd-removal_data_50
|
@TODO DIRSERVER-1030 make this conditional based on the presence of the CascadeControl
public void rename( NextInterceptor next, RenameOperationContext opContext ) throws NamingException
{
LdapDN name = opContext.getDn();
String newRdn = opContext.getNewRdn();
boolean deleteOldRn = opContext.getDelOldDn();
Attributes entry = nexus.lookup( new LookupOperationContext( name ) );
if ( name.startsWith( schemaBaseDN ) )
{
// @TODO DIRSERVER-1030 make this conditional based on the presence of the CascadeControl
schemaManager.modifyRn( name, newRdn, deleteOldRn, entry, false );
}
next.rename( opContext );
}
public void rename( NextInterceptor next, RenameOperationContext opContext ) throws NamingException
{
LdapDN name = opContext.getDn();
String newRdn = opContext.getNewRdn();
boolean deleteOldRn = opContext.getDelOldDn();
Attributes entry = nexus.lookup( new LookupOperationContext( name ) );
if ( name.startsWith( schemaBaseDN ) )
{
schemaManager.modifyRn( name, newRdn, deleteOldRn, entry,
opContext.hasRequestControl( CascadeControl.CONTROL_OID ) );
}
next.rename( opContext );
}
|
core/src/main/java/org/apache/directory/server/core/schema/SchemaService.java
|
satd-removal_data_51
|
TODO: write better code
public void scan(InetAddress address, ScanningResult result) {
// create a scanning subject object, which will be used by fetchers
// to cache common information
ScanningSubject scanningSubject = new ScanningSubject(address);
// populate results
boolean continueScanning = true;
int fetcherIndex = 0;
for (Iterator i = fetcherRegistry.getRegisteredFetchers().iterator(); i.hasNext();) {
Fetcher fetcher = (Fetcher) i.next();
if (continueScanning) {
String value = fetcher.scan(scanningSubject);
// TODO: write better code
if (!Config.getGlobal().scanDeadHosts && fetcher instanceof PingFetcher) {
continueScanning = value != null;
// TODO: hardcoded [timeout]
//value = value == null ? "[timeout]" : value;
}
result.setValue(fetcherIndex, value);
}
// TODO: display something in the else
fetcherIndex++;
}
result.setType(scanningSubject.getResultType());
}
public void scan(InetAddress address, ScanningResult result) {
// create a scanning subject object, which will be used by fetchers
// to cache common information
ScanningSubject scanningSubject = new ScanningSubject(address);
// populate results
int fetcherIndex = 0;
for (Iterator i = fetcherRegistry.getRegisteredFetchers().iterator(); i.hasNext();) {
Fetcher fetcher = (Fetcher) i.next();
if (!scanningSubject.isScanningAborted()) {
String value = fetcher.scan(scanningSubject);
if (value == null)
value = Labels.getInstance().getString("fetcher.value.nothing");
result.setValue(fetcherIndex, value);
}
else {
result.setValue(fetcherIndex, Labels.getInstance().getString("fetcher.value.aborted"));
}
fetcherIndex++;
}
result.setType(scanningSubject.getResultType());
}
|
src/net/azib/ipscan/core/Scanner.java
|
satd-removal_data_52
|
FIXME: Should this also include the classifier?
private void processNativeLibraries(final List<String> commands) throws MojoExecutionException
{
// Examine the native libraries directory for content. This will only be true if:
// a) the directory exists
// b) it contains at least 1 file
final boolean hasValidNativeLibrariesDirectory = nativeLibrariesDirectory != null && nativeLibrariesDirectory.exists() && (nativeLibrariesDirectory.listFiles() != null && nativeLibrariesDirectory.listFiles().length > 0);
// Retrieve any native dependencies or attached artifacts. This may include artifacts from the ndk-build MOJO
final Set<Artifact> artifacts = getNativeDependenciesArtifacts();
final boolean hasValidBuildNativeLibrariesDirectory = ndkOutputDirectory.exists() && (ndkOutputDirectory.listFiles() != null && ndkOutputDirectory.listFiles().length > 0);
if (artifacts.isEmpty() && hasValidNativeLibrariesDirectory && !hasValidBuildNativeLibrariesDirectory)
{
getLog().debug("No native library dependencies detected, will point directly to " + nativeLibrariesDirectory);
// Point directly to the directory in this case - no need to copy files around
commands.add("-nf");
commands.add(nativeLibrariesDirectory.getAbsolutePath());
}
else if (!artifacts.isEmpty() || hasValidNativeLibrariesDirectory || hasValidBuildNativeLibrariesDirectory)
{
// In this case, we may have both .so files in it's normal location
// as well as .so dependencies
// Create the ${project.build.outputDirectory}/libs
final File destinationDirectory = new File(outputDirectory.getAbsolutePath());
if (destinationDirectory.exists())
{
// TODO: Clean it out?
}
else
{
if (!destinationDirectory.mkdir())
{
getLog().debug("Could not create output directory " + outputDirectory);
}
}
// Point directly to the newly created directory
commands.add("-nf");
commands.add(destinationDirectory.getAbsolutePath());
// If we have a valid native libs, copy those files - these already come in the structure required
if (hasValidNativeLibrariesDirectory)
{
copyLocalNativeLibraries(nativeLibrariesDirectory,destinationDirectory);
}
if (hasValidBuildNativeLibrariesDirectory)
{
copyLocalNativeLibraries(ndkOutputDirectory,destinationDirectory);
}
final File finalDestinationDirectory = new File(destinationDirectory, ndkArchitecture);
if (!artifacts.isEmpty())
{
getLog().debug("Copying native library dependencies to " + finalDestinationDirectory);
if (finalDestinationDirectory.exists())
{
}
else
{
if (!finalDestinationDirectory.mkdir())
{
getLog().debug("Could not create output directory " + outputDirectory);
}
}
final DefaultArtifactsResolver artifactsResolver = new DefaultArtifactsResolver(this.artifactResolver, this.localRepository, this.remoteRepositories, true);
final Set<Artifact> resolvedArtifacts = artifactsResolver.resolve(artifacts, getLog());
for (Artifact resolvedArtifact : resolvedArtifacts)
{
final File artifactFile = resolvedArtifact.getFile();
try
{
// FIXME: Should this also include the classifier?
final File file = new File(finalDestinationDirectory, "lib" + resolvedArtifact.getArtifactId() + ".so");
getLog().debug("Copying native dependency " + resolvedArtifact.getArtifactId() + " (" + resolvedArtifact.getGroupId() + ") to " + file);
org.apache.commons.io.FileUtils.copyFile(artifactFile, file);
}
catch (Exception e)
{
getLog().error("Could not copy native dependency: " + e.getMessage(), e);
}
}
}
}
}
private void processNativeLibraries(final List<String> commands) throws MojoExecutionException
{
// Examine the native libraries directory for content. This will only be true if:
// a) the directory exists
// b) it contains at least 1 file
final boolean hasValidNativeLibrariesDirectory = nativeLibrariesDirectory != null && nativeLibrariesDirectory.exists() && (nativeLibrariesDirectory.listFiles() != null && nativeLibrariesDirectory.listFiles().length > 0);
// Retrieve any native dependencies or attached artifacts. This may include artifacts from the ndk-build MOJO
final Set<Artifact> artifacts = getNativeDependenciesArtifacts();
final boolean hasValidBuildNativeLibrariesDirectory = nativeLibrariesOutputDirectory.exists() && (nativeLibrariesOutputDirectory.listFiles() != null && nativeLibrariesOutputDirectory.listFiles().length > 0);
if (artifacts.isEmpty() && hasValidNativeLibrariesDirectory && !hasValidBuildNativeLibrariesDirectory)
{
getLog().debug("No native library dependencies or attached artifacts detected, will point directly to " + nativeLibrariesDirectory);
// Point directly to the directory in this case - no need to copy files around
commands.add("-nf");
commands.add(nativeLibrariesDirectory.getAbsolutePath());
}
else if (!artifacts.isEmpty() || hasValidNativeLibrariesDirectory)
{
// In this case, we may have both .so files in it's normal location
// as well as .so dependencies
// Create the ${project.build.outputDirectory}/libs
File destinationDirectory = new File(nativeLibrariesOutputDirectory.getAbsolutePath());
destinationDirectory.mkdirs();
// Point directly to the directory
commands.add("-nf");
commands.add(destinationDirectory.getAbsolutePath());
// If we have a valid native libs, copy those files - these already come in the structure required
if (hasValidNativeLibrariesDirectory)
{
copyLocalNativeLibraries(nativeLibrariesDirectory,destinationDirectory);
}
if (hasValidBuildNativeLibrariesDirectory)
{
copyLocalNativeLibraries(nativeLibrariesOutputDirectory,destinationDirectory);
}
if (!artifacts.isEmpty())
{
final DefaultArtifactsResolver artifactsResolver = new DefaultArtifactsResolver(this.artifactResolver, this.localRepository, this.remoteRepositories, true);
final Set<Artifact> resolvedArtifacts = artifactsResolver.resolve(artifacts, getLog());
for (Artifact resolvedArtifact : resolvedArtifacts)
{
final File artifactFile = resolvedArtifact.getFile();
try
{
final String artifactId = resolvedArtifact.getArtifactId();
final String filename = artifactId.startsWith("lib") ? artifactId + ".so" : "lib" + artifactId + ".so";
final File finalDestinationDirectory = getFinalDestinationDirectoryFor(resolvedArtifact, destinationDirectory);
final File file = new File(finalDestinationDirectory, filename);
getLog().debug("Copying native dependency " + artifactId + " (" + resolvedArtifact.getGroupId() + ") to " + file );
org.apache.commons.io.FileUtils.copyFile(artifactFile, file);
}
catch (Exception e)
{
throw new MojoExecutionException("Could not copy native dependency.", e);
}
}
}
}
}
|
src/main/java/com/jayway/maven/plugins/android/phase09package/ApkMojo.java
|
satd-removal_data_53
|
TODO: check if in reactor
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
JangarooApps jangarooApps = createJangarooApps(project);
Map<String, List<File>> appNamesToDir = new HashMap<>();
for (JangarooApp jangarooApp : jangarooApps.apps) {
String senchaAppName = SenchaUtils.getSenchaPackageName(jangarooApp.mavenProject);
List<File> appReactorDirs = new ArrayList<>();
do {
// TODO: check if in reactor
appReactorDirs.add(new File(jangarooApp.mavenProject.getBuild().getDirectory() + SenchaUtils.APP_TARGET_DIRECTORY));
jangarooApp = jangarooApp instanceof JangarooAppOverlay ? ((JangarooAppOverlay) jangarooApp).baseApp : null;
} while (jangarooApp != null);
appNamesToDir.put(senchaAppName, appReactorDirs);
}
Dependency rootApp = getRootApp();
String rootAppName = rootApp == null ? null : SenchaUtils.getSenchaPackageName(rootApp.getGroupId(), rootApp.getArtifactId());
FileHelper.createAppsJar(session, archiver, artifactHandlerManager, null, null, appNamesToDir, rootAppName);
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
JangarooApps jangarooApps = createJangarooApps(project);
Map<String, List<File>> appNamesToDirsOrJars = new HashMap<>();
for (JangarooApp jangarooApp : jangarooApps.apps) {
String senchaAppName = SenchaUtils.getSenchaPackageName(jangarooApp.mavenProject);
List<File> appReactorDirs = new ArrayList<>();
do {
appReactorDirs.add(getAppDirOrJar(jangarooApp.mavenProject));
jangarooApp = jangarooApp instanceof JangarooAppOverlay ? ((JangarooAppOverlay) jangarooApp).baseApp : null;
} while (jangarooApp != null);
appNamesToDirsOrJars.put(senchaAppName, appReactorDirs);
}
Dependency rootApp = getRootApp();
String rootAppName = rootApp == null ? null : SenchaUtils.getSenchaPackageName(rootApp.getGroupId(), rootApp.getArtifactId());
FileHelper.createAppsJar(session, archiver, artifactHandlerManager, null, null, appNamesToDirsOrJars, rootAppName);
}
|
jangaroo-maven/jangaroo-maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/PackageAppsMojo.java
|
satd-removal_data_54
|
TODO fix this
@Test
public void getObjectInstance() throws Exception {
Reference resource = new Reference("CassandraClientFactory");
resource.add(new StringRefAddr("url", cassandraUrl));
resource.add(new StringRefAddr("port", Integer.toString(cassandraPort)));
Name jndiName = mock(Name.class);
Context context = new InitialContext();
Hashtable<String, String> environment = new Hashtable<String, String>();
CassandraClientJndiResourcePool cassandraClientJNDIResourcePool =
(CassandraClientJndiResourcePool) factory.getObjectInstance(resource, jndiName, context,
environment);
//CassandraClient cassandraClient = (CassandraClient) cassandraClientJNDIResourcePool.borrowObject();
// TODO fix this
//assertNotNull(cassandraClient);
//assertEquals(cassandraUrl, cassandraClient.getCassandraHost().getHost());
//assertEquals(cassandraPort, cassandraClient.getCassandraHost().getPort());
}
@Test
public void getObjectInstance() throws Exception {
Reference resource = new Reference("CassandraClientFactory");
resource.add(new StringRefAddr("hosts", cassandraUrl));
resource.add(new StringRefAddr("clusterName", clusterName));
resource.add(new StringRefAddr("keyspace", "Keyspace1"));
resource.add(new StringRefAddr("autoDiscoverHosts", "true"));
Name jndiName = mock(Name.class);
Context context = new InitialContext();
Hashtable<String, String> environment = new Hashtable<String, String>();
Keyspace keyspace = (Keyspace) factory.getObjectInstance(resource, jndiName, context, environment);
assertNotNull(keyspace);
assertEquals("Keyspace1",keyspace.getKeyspaceName());
}
|
core/src/test/java/me/prettyprint/cassandra/jndi/CassandraClientJndiResourceFactoryTest.java
|
satd-removal_data_55
|
TODO hosting.com throws 400 when we try to delete a vApp
@Test(enabled = true, dependsOnMethods = "testCompareSizes")
public void testCreateTwoNodesWithRunScript() throws Exception {
try {
client.destroyNodesMatching(withTag(tag));
} catch (HttpResponseException e) {
// TODO hosting.com throws 400 when we try to delete a vApp
} catch (NoSuchElementException e) {
}
refreshTemplate();
try {
nodes = newTreeSet(client.runNodesWithTag(tag, 2, template));
} catch (RunNodesException e) {
nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));
throw e;
}
assertEquals(nodes.size(), 2);
checkNodes(nodes, tag);
NodeMetadata node1 = nodes.first();
NodeMetadata node2 = nodes.last();
// credentials aren't always the same
// assertEquals(node1.getCredentials(), node2.getCredentials());
assertLocationSameOrChild(node1.getLocation(), template.getLocation());
assertLocationSameOrChild(node2.getLocation(), template.getLocation());
checkImageIdMatchesTemplate(node1);
checkImageIdMatchesTemplate(node2);
checkOsMatchesTemplate(node1);
checkOsMatchesTemplate(node2);
}
@Test(enabled = true, dependsOnMethods = "testCompareSizes")
public void testCreateTwoNodesWithRunScript() throws Exception {
try {
client.destroyNodesMatching(withTag(tag));
} catch (NoSuchElementException e) {
}
refreshTemplate();
try {
nodes = newTreeSet(client.runNodesWithTag(tag, 2, template));
} catch (RunNodesException e) {
nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));
throw e;
}
assertEquals(nodes.size(), 2);
checkNodes(nodes, tag);
NodeMetadata node1 = nodes.first();
NodeMetadata node2 = nodes.last();
// credentials aren't always the same
// assertEquals(node1.getCredentials(), node2.getCredentials());
assertLocationSameOrChild(node1.getLocation(), template.getLocation());
assertLocationSameOrChild(node2.getLocation(), template.getLocation());
checkImageIdMatchesTemplate(node1);
checkImageIdMatchesTemplate(node2);
checkOsMatchesTemplate(node1);
checkOsMatchesTemplate(node2);
}
|
compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java
|
satd-removal_data_56
|
TODO merge SMS into secondary action
private void populateContactAndAboutCard() {
Trace.beginSection("bind contact card");
final List<Entry> contactCardEntries = new ArrayList<>();
final List<Entry> aboutCardEntries = new ArrayList<>();
int topContactIndex = 0;
for (int i = 0; i < mDataItemsList.size(); ++i) {
final List<DataItem> dataItemsByMimeType = mDataItemsList.get(i);
final DataItem topDataItem = dataItemsByMimeType.get(0);
if (ABOUT_CARD_MIMETYPES.contains(topDataItem.getMimeType())) {
aboutCardEntries.addAll(dataItemsToEntries(mDataItemsList.get(i)));
} else {
// Add most used to the top of the contact card
final Entry topEntry = dataItemToEntry(topDataItem);
if (topEntry != null) {
contactCardEntries.add(topContactIndex++, dataItemToEntry(topDataItem));
}
// TODO merge SMS into secondary action
if (topDataItem instanceof PhoneDataItem) {
final PhoneDataItem phone = (PhoneDataItem) topDataItem;
Intent smsIntent = null;
if (mSmsComponent != null) {
smsIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(CallUtil.SCHEME_SMSTO, phone.getNumber(), null));
smsIntent.setComponent(mSmsComponent);
}
final int dataId = phone.getId() > Integer.MAX_VALUE ?
-1 : (int) phone.getId();
contactCardEntries.add(topContactIndex++,
new Entry(dataId,
getResources().getDrawable(R.drawable.ic_message_24dp),
getResources().getString(R.string.send_message),
/* subHeader = */ null,
/* text = */ phone.buildDataString(
this, topDataItem.getDataKind()),
smsIntent,
/* isEditable = */ false));
}
// Add the rest of the entries to the bottom of the card
if (dataItemsByMimeType.size() > 1) {
contactCardEntries.addAll(dataItemsToEntries(
dataItemsByMimeType.subList(1, dataItemsByMimeType.size())));
}
}
}
if (contactCardEntries.size() > 0) {
mContactCard.initialize(contactCardEntries,
/* numInitialVisibleEntries = */ MIN_NUM_CONTACT_ENTRIES_SHOWN,
/* isExpanded = */ false,
mExpandingEntryCardViewListener);
mContactCard.setVisibility(View.VISIBLE);
} else {
mContactCard.setVisibility(View.GONE);
}
Trace.endSection();
Trace.beginSection("bind about card");
mAboutCard.initialize(aboutCardEntries,
/* numInitialVisibleEntries = */ 1,
/* isExpanded = */ true,
mExpandingEntryCardViewListener);
Trace.endSection();
}
private void populateContactAndAboutCard() {
Trace.beginSection("bind contact card");
final List<List<Entry>> contactCardEntries = new ArrayList<>();
final List<List<Entry>> aboutCardEntries = new ArrayList<>();
for (int i = 0; i < mDataItemsList.size(); ++i) {
final List<DataItem> dataItemsByMimeType = mDataItemsList.get(i);
final DataItem topDataItem = dataItemsByMimeType.get(0);
if (ABOUT_CARD_MIMETYPES.contains(topDataItem.getMimeType())) {
List<Entry> aboutEntries = dataItemsToEntries(mDataItemsList.get(i));
if (aboutEntries.size() > 0) {
aboutCardEntries.add(aboutEntries);
}
} else {
List<Entry> contactEntries = dataItemsToEntries(mDataItemsList.get(i));
if (contactEntries.size() > 0) {
contactCardEntries.add(contactEntries);
}
}
}
if (contactCardEntries.size() > 0) {
mContactCard.initialize(contactCardEntries,
/* numInitialVisibleEntries = */ MIN_NUM_CONTACT_ENTRIES_SHOWN,
/* isExpanded = */ false,
mExpandingEntryCardViewListener);
mContactCard.setVisibility(View.VISIBLE);
} else {
mContactCard.setVisibility(View.GONE);
}
Trace.endSection();
Trace.beginSection("bind about card");
mAboutCard.initialize(aboutCardEntries,
/* numInitialVisibleEntries = */ 1,
/* isExpanded = */ true,
mExpandingEntryCardViewListener);
Trace.endSection();
}
|
src/com/android/contacts/quickcontact/QuickContactActivity.java
|
satd-removal_data_57
|
TODO check possible weld bug
@Test
@SpecAssertions({ @SpecAssertion(section = "5.6", id = "e"), @SpecAssertion(section = "5.6.3", id = "b") })
@SuppressWarnings("serial")
public void testNewBean() {
// TODO check possible weld bug
// Instance<List<String>> instance = getInstanceByType(ObtainsNewInstanceBean.class).getStrings();
// assert instance.select(new TypeLiteral<ArrayList<String>>(){}).get() instanceof ArrayList<?>;
String instance = getInstanceByType(ObtainsNewInstanceBean.class).getString();
assert instance != null && instance instanceof String;
getInstanceByType(ObtainsNewInstanceBean.class).getMap();
}
@Test
@SpecAssertions({ @SpecAssertion(section = "5.6", id = "e"), @SpecAssertion(section = "5.6.3", id = "b") })
public void testNewBean() {
Instance<String> string = getInstanceByType(ObtainsNewInstanceBean.class).getString();
assert !string.isAmbiguous();
assert !string.isUnsatisfied();
assert string.get() != null;
assert string.get() instanceof String;
Instance<Map<String, String>> map = getInstanceByType(ObtainsNewInstanceBean.class).getMap();
assert !map.isAmbiguous();
assert !map.isUnsatisfied();
Map<String, String> instance = map.get();
assert instance != null;
assert instance instanceof HashMap<?, ?>;
}
|
impl/src/main/java/org/jboss/cdi/tck/tests/lookup/dynamic/DynamicLookupTest.java
|
satd-removal_data_58
|
todo: alias sub-index
public synchronized void initializeCommands() {
// ** Load topics from highest to lowest priority order **
// todo: ignore specified plugins
Set<String> ignoredPlugins = Collections.emptySet();
// Don't load any automatic help topics if All is ignored
if (ignoredPlugins.contains("All")) {
return;
}
// Initialize help topics from the server's command map
outer:
for (Command command : server.getCommandMap().getCommands()) {
if (commandInIgnoredPlugin(command, ignoredPlugins)) {
continue;
}
// Register a topic
for (Class<?> c : topicFactoryMap.keySet()) {
if (c.isAssignableFrom(command.getClass())) {
HelpTopic t = topicFactoryMap.get(c).createTopic(command);
if (t != null) addTopic(t);
continue outer;
}
if (command instanceof PluginCommand && c.isAssignableFrom(((PluginCommand) command).getExecutor().getClass())) {
HelpTopic t = topicFactoryMap.get(c).createTopic(command);
if (t != null) addTopic(t);
continue outer;
}
}
addTopic(new GenericCommandHelpTopic(command));
}
// todo: help on alias topics
// todo: alias sub-index
// Initialize plugin-level sub-topics
Map<String, Set<HelpTopic>> pluginIndexes = new HashMap<>();
fillPluginIndexes(pluginIndexes, server.getCommandMap().getCommands());
for (Map.Entry<String, Set<HelpTopic>> entry : pluginIndexes.entrySet()) {
addTopic(new IndexHelpTopic(entry.getKey(), "All commands for " + entry.getKey(), null, entry.getValue(), "Below is a list of all " + entry.getKey() + " commands:"));
}
// todo: amended topics from help.yml
}
public synchronized void initializeCommands() {
// Don't load any automatic help topics if All is ignored
if (ignoredPlugins.contains("All")) {
return;
}
Collection<Command> commands = server.getCommandMap().getCommands();
// Initialize help topics from the server's command map
outer:
for (Command command : commands) {
if (commandInIgnoredPlugin(command)) {
continue;
}
// Register a topic
for (Class<?> c : topicFactoryMap.keySet()) {
if (c.isAssignableFrom(command.getClass())) {
HelpTopic t = topicFactoryMap.get(c).createTopic(command);
if (t != null) addCommandTopic(t);
continue outer;
}
if (command instanceof PluginCommand && c.isAssignableFrom(((PluginCommand) command).getExecutor().getClass())) {
HelpTopic t = topicFactoryMap.get(c).createTopic(command);
if (t != null) addCommandTopic(t);
continue outer;
}
}
addCommandTopic(new GenericCommandHelpTopic(command));
}
// Alias topics for commands
Set<HelpTopic> aliases = new TreeSet<>(TOPIC_COMPARE);
for (Command command : commands) {
if (commandInIgnoredPlugin(command)) {
continue;
}
HelpTopic original = getHelpTopic("/" + command.getLabel());
if (original != null) {
for (String alias : command.getAliases()) {
HelpTopic aliasTopic = new AliasTopic("/" + alias, original);
if (!helpTopics.containsKey(aliasTopic.getName())) {
aliases.add(aliasTopic);
addPrivateTopic(aliasTopic);
}
}
}
}
// Aliases index topic
if (!aliases.isEmpty()) {
addTopic(new IndexHelpTopic("Aliases", "Lists command aliases", null, aliases, null));
}
// Initialize plugin-level sub-topics
Map<String, Set<HelpTopic>> pluginIndexes = new HashMap<>();
for (Command command : commands) {
String pluginName = getCommandPluginName(command);
if (pluginName != null) {
HelpTopic topic = getHelpTopic("/" + command.getLabel());
if (topic != null) {
if (!pluginIndexes.containsKey(pluginName)) {
pluginIndexes.put(pluginName, new TreeSet<>(TOPIC_COMPARE));
}
pluginIndexes.get(pluginName).add(topic);
}
}
}
for (Map.Entry<String, Set<HelpTopic>> entry : pluginIndexes.entrySet()) {
String key = entry.getKey();
addTopic(new IndexHelpTopic(key, "All commands for " + key, null, entry.getValue(), "Below is a list of all " + key + " commands:"));
}
}
|
src/main/java/net/glowstone/util/GlowHelpMap.java
|
satd-removal_data_59
|
TODO srowen says cluster is not used?
public void testFuzzyKMeansMapper() throws Exception {
List<Vector> points = TestKmeansClustering
.getPoints(TestKmeansClustering.reference);
DistanceMeasure measure = new EuclideanDistanceMeasure();
SoftCluster.config(measure, 0.001);
for (int k = 0; k < points.size(); k++) {
System.out.println("testKFuzzyKMeansMRJob k= " + k);
// pick k initial cluster centers at random
List<SoftCluster> clusterList = new ArrayList<SoftCluster>();
for (int i = 0; i < k + 1; i++) {
Vector vec = tweakValue(points.get(i));
SoftCluster cluster = new SoftCluster(vec);
cluster.addPoint(cluster.getCenter(), 1);
clusterList.add(cluster);
}
// run mapper
FuzzyKMeansMapper mapper = new FuzzyKMeansMapper();
mapper.config(clusterList);
DummyOutputCollector<Text, Text> mapCollector = new DummyOutputCollector<Text, Text>();
for (Vector point : points) {
mapper.map(new Text(), new Text(point.asFormatString()), mapCollector,
null);
}
// now verify mapper output
assertEquals("Mapper Keys", k + 1, mapCollector.getData().size());
Map<String, Double> pointTotalProbMap = new HashMap<String, Double>();
for (String key : mapCollector.getKeys()) {
//SoftCluster cluster = SoftCluster.decodeCluster(key);
// TODO srowen says cluster is not used?
List<Text> values = mapCollector.getValue(key);
for (Text value : values) {
String pointInfo = value.toString();
double pointProb = Double.parseDouble(pointInfo.substring(0,
pointInfo.indexOf(":")));
String encodedVector = pointInfo
.substring(pointInfo.indexOf(":") + 1);
Double val = pointTotalProbMap.get(encodedVector);
double probVal = 0.0;
if (val != null) {
probVal = val;
}
pointTotalProbMap.put(encodedVector, probVal + pointProb);
}
}
for (Map.Entry<String, Double> entry : pointTotalProbMap.entrySet()) {
String key = entry.getKey();
double value = round(entry.getValue(), 1);
assertEquals("total Prob for Point:" + key, 1.0, value);
}
}
}
public void testFuzzyKMeansMapper() throws Exception {
List<Vector> points = TestKmeansClustering
.getPoints(TestKmeansClustering.reference);
DistanceMeasure measure = new EuclideanDistanceMeasure();
SoftCluster.config(measure, 0.001);
for (int k = 0; k < points.size(); k++) {
System.out.println("testKFuzzyKMeansMRJob k= " + k);
// pick k initial cluster centers at random
List<SoftCluster> clusterList = new ArrayList<SoftCluster>();
for (int i = 0; i < k + 1; i++) {
Vector vec = tweakValue(points.get(i));
SoftCluster cluster = new SoftCluster(vec);
cluster.addPoint(cluster.getCenter(), 1);
clusterList.add(cluster);
}
// run mapper
FuzzyKMeansMapper mapper = new FuzzyKMeansMapper();
mapper.config(clusterList);
DummyOutputCollector<Text, Text> mapCollector = new DummyOutputCollector<Text, Text>();
for (Vector point : points) {
mapper.map(new Text(), new Text(point.asFormatString()), mapCollector,
null);
}
// now verify mapper output
assertEquals("Mapper Keys", k + 1, mapCollector.getData().size());
Map<String, Double> pointTotalProbMap = new HashMap<String, Double>();
for (String key : mapCollector.getKeys()) {
//SoftCluster cluster = SoftCluster.decodeCluster(key);
List<Text> values = mapCollector.getValue(key);
for (Text value : values) {
String pointInfo = value.toString();
double pointProb = Double.parseDouble(pointInfo.substring(0,
pointInfo.indexOf(':')));
String encodedVector = pointInfo
.substring(pointInfo.indexOf(':') + 1);
Double val = pointTotalProbMap.get(encodedVector);
double probVal = 0.0;
if (val != null) {
probVal = val;
}
pointTotalProbMap.put(encodedVector, probVal + pointProb);
}
}
for (Map.Entry<String, Double> entry : pointTotalProbMap.entrySet()) {
String key = entry.getKey();
double value = round(entry.getValue(), 1);
assertEquals("total Prob for Point:" + key, 1.0, value);
}
}
}
|
core/src/test/java/org/apache/mahout/clustering/fuzzykmeans/TestFuzzyKmeansClustering.java
|
satd-removal_data_60
|
TODO: get previous document
private void saveDocument(String comment) throws SAXException
{
try {
XWikiContext context = getXWikiContext();
XWikiDocument document = getDocument();
XWikiDocument dbDocument = getDatabaseDocument();
// TODO: get previous document
// TODO: diff previous and new document
// TODO: if there is differences
// TODO: ..apply diff to db document
} catch (Exception e) {
throw new SAXException("Failed to save document", e);
}
this.needSave = false;
}
private void saveDocument(String comment) throws SAXException
{
try {
XWikiContext context = getXWikiContext();
XWikiDocument document = getDocument();
XWikiDocument dbDocument = getDatabaseDocument().clone();
XWikiDocument previousDocument = getPreviousDocument();
if (previousDocument != null) {
if (merge(previousDocument, document, dbDocument).isModified()) {
context.getWiki().saveDocument(document, comment, context);
}
} else {
if (!dbDocument.isNew()) {
document.setVersion(dbDocument.getVersion());
}
context.getWiki().saveDocument(document, comment, context);
}
} catch (Exception e) {
throw new SAXException("Failed to save document", e);
}
}
|
xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-handlers/xwiki-platform-extension-handler-xar/src/main/java/org/xwiki/extension/xar/internal/handler/packager/xml/DocumentImporterHandler.java
|
satd-removal_data_61
|
TODO: use return value to determine container exit status
@Override
protected void runInternal() {
// TODO: use return value to determine container exit status
ContainerHandler containerHandler = beanFactory.getBean(ContainerHandler.class);
try {
Object result = containerHandler.handle(this);
log.info("Result from container handle: " + result);
} catch (Exception e) {
log.error("Error handling container", e);
}
}
@Override
protected void runInternal() {
Exception runtimeException = null;
Object result = null;
try {
ContainerHandler containerHandler = beanFactory.getBean(ContainerHandler.class);
result = containerHandler.handle(this);
} catch (Exception e) {
runtimeException = e;
log.error("Error handling container", e);
}
log.info("Container state based on result=[" + result + "] runtimeException=[" + runtimeException + "]");
if (runtimeException != null) {
notifyContainerState(ContainerState.FAILED, 1);
} else if (result != null && result instanceof Integer) {
int val = ((Integer)result).intValue();
if (val < 0) {
notifyContainerState(ContainerState.FAILED, val);
} else {
notifyContainerState(ContainerState.COMPLETED, val);
}
} else if (result != null && result instanceof Boolean) {
boolean val = ((Boolean)result).booleanValue();
if (val) {
notifyContainerState(ContainerState.COMPLETED, 0);
} else {
notifyContainerState(ContainerState.FAILED, -1);
}
} else {
notifyCompleted();
}
}
|
spring-yarn/spring-yarn-core/src/main/java/org/springframework/yarn/container/DefaultYarnContainer.java
|
satd-removal_data_62
|
TODO switch to DOM4J for simplicity and consistency
public void transformPom(MavenCoordinates coreCoordinates) throws PomTransformationException{
File pom = new File(rootDir.getAbsolutePath()+"/"+pomFileName);
File backupedPom = new File(rootDir.getAbsolutePath()+"/"+pomFileName+".backup");
try {
FileUtils.rename(pom, backupedPom);
Source xmlSource = new StreamSource(backupedPom);
// TODO switch to DOM4J for simplicity and consistency
Source xsltSource = new StreamSource(new ClassPathResource("mavenParentReplacer.xsl").getInputStream());
Result result = new StreamResult(pom);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(xsltSource);
transformer.setParameter("parentArtifactId", coreCoordinates.artifactId);
transformer.setParameter("parentGroupId", coreCoordinates.groupId);
transformer.setParameter("parentVersion", coreCoordinates.version);
transformer.transform(xmlSource, result);
} catch (Exception e) {
throw new PomTransformationException("Error while transforming pom : "+pom.getAbsolutePath(), e);
}
}
public void transformPom(MavenCoordinates coreCoordinates) throws PomTransformationException{
File pom = new File(rootDir.getAbsolutePath()+"/"+pomFileName);
File backupedPom = new File(rootDir.getAbsolutePath()+"/"+pomFileName+".backup");
try {
FileUtils.rename(pom, backupedPom);
Document doc;
try {
doc = new SAXReader().read(backupedPom);
} catch (DocumentException x) {
throw new IOException(x);
}
Element parent = doc.getRootElement().element("parent");
if (parent != null) {
Element groupIdElem = parent.element(GROUP_ID_ELEMENT);
if (groupIdElem != null) {
groupIdElem.setText(coreCoordinates.groupId);
}
Element artifactIdElem = parent.element(ARTIFACT_ID_ELEMENT);
if (artifactIdElem != null) {
artifactIdElem.setText(coreCoordinates.artifactId);
}
Element versionIdElem = parent.element(VERSION_ELEMENT);
if (versionIdElem != null) {
versionIdElem.setText(coreCoordinates.version);
}
}
writeDocument(pom, doc);
} catch (Exception e) {
throw new PomTransformationException("Error while transforming pom : "+pom.getAbsolutePath(), e);
}
}
|
plugins-compat-tester/src/main/java/org/jenkins/tools/test/model/MavenPom.java
|
satd-removal_data_63
|
TODO fill in address index
public void indexingAddresses(final IProgress progress){
File file = new File(Environment.getExternalStorageDirectory(), ADDRESS_PATH);
closeAddresses();
if (file.exists() && file.canRead()) {
for (File f : file.listFiles()) {
if (f.getName().endsWith(IndexConstants.ADDRESS_INDEX_EXT)) {
// TODO fill in address index
}
}
}
}
public void indexingAddresses(final IProgress progress){
File file = new File(Environment.getExternalStorageDirectory(), ADDRESS_PATH);
closeAddresses();
if (file.exists() && file.canRead()) {
for (File f : file.listFiles()) {
if (f.getName().endsWith(IndexConstants.ADDRESS_INDEX_EXT)) {
RegionAddressRepository repository = new RegionAddressRepository();
progress.startTask("Indexing address" + f.getName(), -1);
repository.initialize(progress, f);
addressMap.put(repository.getName(), repository);
}
}
}
}
|
OsmAnd/src/com/osmand/ResourceManager.java
|
satd-removal_data_64
|
TODO: read all contacts part of this aggregate and hook into tabs
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
final Context context = this;
mInflater = getLayoutInflater();
mResolver = getContentResolver();
mContentView = (ViewGroup)mInflater.inflate(R.layout.act_edit, null);
mTabContent = (ViewGroup)mContentView.findViewById(android.R.id.tabcontent);
setContentView(mContentView);
// Setup floating buttons
findViewById(R.id.btn_done).setOnClickListener(this);
findViewById(R.id.btn_discard).setOnClickListener(this);
final Intent intent = getIntent();
final String action = intent.getAction();
final Bundle extras = intent.getExtras();
mUri = intent.getData();
// TODO: read all contacts part of this aggregate and hook into tabs
// Resolve the intent
if (Intent.ACTION_EDIT.equals(action) && mUri != null) {
try {
final long aggId = ContentUris.parseId(mUri);
final EntityIterator iterator = mResolver.queryEntities(
ContactsContract.RawContacts.CONTENT_URI,
ContactsContract.RawContacts.CONTACT_ID + "=" + aggId, null, null);
while (iterator.hasNext()) {
final Entity before = iterator.next();
final EntityDelta entity = EntityDelta.fromBefore(before);
mEntities.add(entity);
Log.d(TAG, "Loaded entity...");
}
iterator.close();
} catch (RemoteException e) {
Log.d(TAG, "Problem reading aggregate", e);
}
// if (icicle == null) {
// // Build the entries & views
// buildEntriesForEdit(extras);
// buildViews();
// }
setTitle(R.string.editContact_title_edit);
} else if (Intent.ACTION_INSERT.equals(action)) {
// if (icicle == null) {
// // Build the entries & views
// buildEntriesForInsert(extras);
// buildViews();
// }
// setTitle(R.string.editContact_title_insert);
// mState = STATE_INSERT;
}
// if (mState == STATE_UNKNOWN) {
// Log.e(TAG, "Cannot resolve intent: " + intent);
// finish();
// return;
// }
mEditor = new ContactEditorView(context);
mTabContent.removeAllViews();
mTabContent.addView(mEditor.getView());
// final ContactsSource source = Sources.getInstance().getKindsForAccountType(
// Sources.ACCOUNT_TYPE_GOOGLE);
final ContactsSource source = Sources.getInstance().getKindsForAccountType(
Sources.ACCOUNT_TYPE_EXCHANGE);
mEditor.setState(mEntities.get(0), source);
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
final Context context = this;
final LayoutInflater inflater = this.getLayoutInflater();
setContentView(R.layout.act_edit);
mTabContent = this.findViewById(android.R.id.tabcontent);
mEditor = new ContactEditorView(context);
mEditor.swapWith(mTabContent);
findViewById(R.id.btn_done).setOnClickListener(this);
findViewById(R.id.btn_discard).setOnClickListener(this);
final Intent intent = getIntent();
final String action = intent.getAction();
final Bundle extras = intent.getExtras();
mUri = intent.getData();
mSources = Sources.getInstance();
if (Intent.ACTION_EDIT.equals(action) && icicle == null) {
// Read initial state from database
readEntities();
rebuildTabs();
}
}
|
src/com/android/contacts/ui/EditContactActivity.java
|
satd-removal_data_65
|
TODO: Better player check!
public void run() {
synchronized (sessions) {
for (Iterator<Map.Entry<String, Map<Class<? extends PersistentSession>, PersistentSession>>>
i = sessions.entrySet().iterator(); i.hasNext();) {
Map.Entry<String, Map<Class<? extends PersistentSession>, PersistentSession>> entry = i.next();
if (entry.getKey().equals(CommandBook.server().getConsoleSender().getName())) { // TODO: Better player check!
continue;
}
final Player player = CommandBook.server().getPlayerExact(entry.getKey());
if (player != null && player.isOnline()) {
continue;
}
for (Iterator<PersistentSession> i2 = entry.getValue().values().iterator(); i2.hasNext(); ) {
if (!i2.next().isRecent()) {
i2.remove();
}
}
if (entry.getValue().size() == 0) {
i.remove();
}
}
}
}
public void run() {
synchronized (sessions) {
outer: for (Iterator<Map.Entry<String, Map<Class<? extends PersistentSession>, PersistentSession>>>
i = sessions.entrySet().iterator(); i.hasNext();) {
Map.Entry<String, Map<Class<? extends PersistentSession>, PersistentSession>> entry = i.next();
for (Iterator<PersistentSession> i2 = entry.getValue().values().iterator(); i2.hasNext(); ) {
PersistentSession sess = i2.next();
if (sess.getOwner() != null) {
continue outer;
}
if (!sess.isRecent()) {
i2.remove();
}
}
if (entry.getValue().size() == 0) {
i.remove();
}
}
}
}
|
src/main/java/com/sk89q/commandbook/session/SessionComponent.java
|
satd-removal_data_66
|
TODO: make non-hardwired
public void start() {
// TODO: make non-hardwired
setFilePattern( "hbmlint-result.txt" );
getProperties().put(TEMPLATE_NAME, TEXT_REPORT_FTL);
super.start();
}
public void start() {
getProperties().put(TEMPLATE_NAME, TEXT_REPORT_FTL);
getProperties().put(FILE_PATTERN, "hbmlint-result.txt");
super.start();
}
|
orm/src/main/java/org/hibernate/tool/internal/export/lint/HbmLintExporter.java
|
satd-removal_data_67
|
FIXME: this is just wrong for implementing members()
protected void init(){
com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface declaration = (com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface) this.declaration;
ProducedType superType = declaration.getExtendedType();
if(superType != null)
this.superclass = (ceylon.language.metamodel.untyped.ParameterisedType<ceylon.language.metamodel.untyped.Class>) Metamodel.getMetamodel(superType);
List<ProducedType> satisfiedTypes = declaration.getSatisfiedTypes();
ceylon.language.metamodel.untyped.ParameterisedType<ceylon.language.metamodel.untyped.Interface>[] interfaces = new ceylon.language.metamodel.untyped.ParameterisedType[satisfiedTypes.size()];
int i=0;
for(ProducedType pt : satisfiedTypes){
interfaces[i++] = (ceylon.language.metamodel.untyped.ParameterisedType<ceylon.language.metamodel.untyped.Interface>) Metamodel.getMetamodel(pt);
}
this.interfaces = (Sequential)Util.sequentialInstance($InterfacesTypeDescriptor, interfaces);
List<com.redhat.ceylon.compiler.typechecker.model.TypeParameter> typeParameters = declaration.getTypeParameters();
ceylon.language.metamodel.untyped.TypeParameter[] typeParametersArray = new ceylon.language.metamodel.untyped.TypeParameter[typeParameters.size()];
i=0;
for(com.redhat.ceylon.compiler.typechecker.model.TypeParameter tp : typeParameters){
typeParametersArray[i++] = new com.redhat.ceylon.compiler.java.runtime.metamodel.FreeTypeParameter(tp);
}
this.typeParameters = (Sequential)Util.sequentialInstance(ceylon.language.metamodel.untyped.TypeParameter.$TypeDescriptor, typeParametersArray);
List<com.redhat.ceylon.compiler.typechecker.model.Declaration> memberModelDeclarations = declaration.getMembers();
i=0;
List<ceylon.language.metamodel.untyped.Member<FreeFunction>> functions = new LinkedList<ceylon.language.metamodel.untyped.Member<FreeFunction>>();
List<ceylon.language.metamodel.untyped.Member<FreeValue>> values = new LinkedList<ceylon.language.metamodel.untyped.Member<FreeValue>>();
List<ceylon.language.metamodel.untyped.Member<FreeClassOrInterface>> types = new LinkedList<ceylon.language.metamodel.untyped.Member<FreeClassOrInterface>>();
// FIXME: this is just wrong for implementing members()
for(com.redhat.ceylon.compiler.typechecker.model.Declaration memberModelDeclaration : memberModelDeclarations){
if(memberModelDeclaration instanceof Method){
functions.add(new FreeMember(this, new FreeFunction((Method) memberModelDeclaration)));
}else if(memberModelDeclaration instanceof com.redhat.ceylon.compiler.typechecker.model.Value){
values.add(new FreeMember(this, new FreeValue((MethodOrValue) memberModelDeclaration)));
}else if(memberModelDeclaration instanceof com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface){
types.add(new FreeMember(this, Metamodel.getOrCreateMetamodel(memberModelDeclaration)));
}
}
TypeDescriptor functionMemberTD = TypeDescriptor.klass(ceylon.language.metamodel.untyped.Member.class, $FunctionTypeDescriptor);
this.functions = (Sequential)Util.sequentialInstance(functionMemberTD, functions.toArray(new ceylon.language.metamodel.untyped.Member[functions.size()]));
TypeDescriptor valueMemberTD = TypeDescriptor.klass(ceylon.language.metamodel.untyped.Member.class, $ValueTypeDescriptor);
this.values = (Sequential)Util.sequentialInstance(valueMemberTD, values.toArray(new ceylon.language.metamodel.untyped.Member[values.size()]));
TypeDescriptor typesMemberTD = TypeDescriptor.klass(ceylon.language.metamodel.untyped.Member.class, $ClassOrInterfaceTypeDescriptor);
this.types = (Sequential)Util.sequentialInstance(typesMemberTD, types.toArray(new ceylon.language.metamodel.untyped.Member[types.size()]));
}
protected void init(){
com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface declaration = (com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface) this.declaration;
ProducedType superType = declaration.getExtendedType();
if(superType != null)
this.superclass = (ceylon.language.metamodel.untyped.ParameterisedType<ceylon.language.metamodel.untyped.Class>) Metamodel.getMetamodel(superType);
List<ProducedType> satisfiedTypes = declaration.getSatisfiedTypes();
ceylon.language.metamodel.untyped.ParameterisedType<ceylon.language.metamodel.untyped.Interface>[] interfaces = new ceylon.language.metamodel.untyped.ParameterisedType[satisfiedTypes.size()];
int i=0;
for(ProducedType pt : satisfiedTypes){
interfaces[i++] = (ceylon.language.metamodel.untyped.ParameterisedType<ceylon.language.metamodel.untyped.Interface>) Metamodel.getMetamodel(pt);
}
this.interfaces = (Sequential)Util.sequentialInstance($InterfacesTypeDescriptor, interfaces);
List<com.redhat.ceylon.compiler.typechecker.model.TypeParameter> typeParameters = declaration.getTypeParameters();
ceylon.language.metamodel.untyped.TypeParameter[] typeParametersArray = new ceylon.language.metamodel.untyped.TypeParameter[typeParameters.size()];
i=0;
for(com.redhat.ceylon.compiler.typechecker.model.TypeParameter tp : typeParameters){
typeParametersArray[i++] = new com.redhat.ceylon.compiler.java.runtime.metamodel.FreeTypeParameter(tp);
}
this.typeParameters = (Sequential)Util.sequentialInstance(ceylon.language.metamodel.untyped.TypeParameter.$TypeDescriptor, typeParametersArray);
List<com.redhat.ceylon.compiler.typechecker.model.Declaration> memberModelDeclarations = declaration.getMembers();
i=0;
this.declarations = new LinkedList<ceylon.language.metamodel.untyped.Declaration>();
for(com.redhat.ceylon.compiler.typechecker.model.Declaration memberModelDeclaration : memberModelDeclarations){
if(memberModelDeclaration instanceof Method){
declarations.add(new FreeFunction((Method) memberModelDeclaration));
}else if(memberModelDeclaration instanceof com.redhat.ceylon.compiler.typechecker.model.Value){
declarations.add(new FreeValue((MethodOrValue) memberModelDeclaration));
}else if(memberModelDeclaration instanceof com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface){
declarations.add(Metamodel.getOrCreateMetamodel(memberModelDeclaration));
}
}
}
|
runtime/com/redhat/ceylon/compiler/java/runtime/metamodel/FreeClassOrInterface.java
|
satd-removal_data_68
|
TODO: This is not a real implementation we want to work with
private void resolve(final IPackageFragmentRoot packageRoot) {
// TODO: This is not a real implementation we want to work with
if (packageRoot instanceof JarPackageFragmentRoot) {
final String name = packageRoot.getPath().lastSegment();
if (name.matches("org\\.eclipse\\..+")) {
callsModelIndex.setResolved(packageRoot, new LibraryIdentifier("org.eclipse", Version.create(3, 6)));
return;
}
}
callsModelIndex.setResolved(packageRoot, LibraryIdentifier.UNKNOWN);
}
private void resolve(final IPackageFragmentRoot packageRoot) {
if (packageRoot instanceof JarPackageFragmentRoot) {
try {
final ArchiveDetailsExtractor extractor = new ArchiveDetailsExtractor(packageRoot.getPath().toFile());
final LibraryIdentifier libraryIdentifier = new LibraryIdentifier(extractor.extractName(),
extractor.extractVersion());
callsModelIndex.setResolved(packageRoot, libraryIdentifier);
} catch (final IOException e) {
e.printStackTrace();
}
}
}
|
org.eclipse.recommenders.rcp.codecompletion.calls/src/org/eclipse/recommenders/internal/rcp/codecompletion/calls/store/LibraryIdentifierResolverJob.java
|
satd-removal_data_69
|
XXX implement actions
private void createProfilesSection(FormToolkit toolkit, Composite body) {
Section profilesSection = toolkit.createSection(body, Section.TITLE_BAR);
profilesSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 3));
profilesSection.setText("Profiles");
profilesEditor = new ListEditorComposite<Profile>(profilesSection, SWT.NONE);
profilesSection.setClient(profilesEditor);
toolkit.adapt(profilesEditor);
toolkit.paintBordersFor(profilesEditor);
profilesEditor.setContentProvider(new ListEditorContentProvider<Profile>());
profilesEditor.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
if(element instanceof Profile) {
String profileId = ((Profile) element).getId();
return profileId==null || profileId.length()==0 ? "[unknown]" : profileId;
}
return super.getText(element);
}
public Image getImage(Object element) {
return MavenEditorImages.IMG_PROFILE;
}
});
profilesEditor.addSelectionListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
List<Profile> selection = profilesEditor.getSelection();
updateProfileDetails(selection.size()==1 ? selection.get(0) : null);
}
});
// XXX implement actions
profilesEditor.setReadOnly(pomEditor.isReadOnly());
}
private void createProfilesSection(FormToolkit toolkit, Composite body) {
Section profilesSection = toolkit.createSection(body, Section.TITLE_BAR);
profilesSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 3));
profilesSection.setText("Profiles");
profilesEditor = new ListEditorComposite<Profile>(profilesSection, SWT.NONE);
profilesSection.setClient(profilesEditor);
toolkit.adapt(profilesEditor);
toolkit.paintBordersFor(profilesEditor);
profilesEditor.setContentProvider(new ListEditorContentProvider<Profile>());
profilesEditor.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
if(element instanceof Profile) {
String profileId = ((Profile) element).getId();
return isEmpty(profileId) ? "?" : profileId;
}
return super.getText(element);
}
public Image getImage(Object element) {
return MavenEditorImages.IMG_PROFILE;
}
});
profilesEditor.addSelectionListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
List<Profile> selection = profilesEditor.getSelection();
updateProfileDetails(selection.size()==1 ? selection.get(0) : null);
}
});
profilesEditor.setAddListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
CompoundCommand compoundCommand = new CompoundCommand();
EditingDomain editingDomain = getEditingDomain();
ProfilesType profiles = model.getProfiles();
if(profiles == null) {
profiles = PomFactory.eINSTANCE.createProfilesType();
Command command = SetCommand.create(editingDomain, model, POM_PACKAGE.getModel_Profiles(), profiles);
compoundCommand.append(command);
}
Profile profile = PomFactory.eINSTANCE.createProfile();
Command addCommand = AddCommand.create(editingDomain, profiles, POM_PACKAGE.getProfilesType_Profile(), profile);
compoundCommand.append(addCommand);
editingDomain.getCommandStack().execute(compoundCommand);
profilesEditor.setSelection(Collections.singletonList(profile));
}
});
profilesEditor.setRemoveListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
CompoundCommand compoundCommand = new CompoundCommand();
EditingDomain editingDomain = getEditingDomain();
List<Profile> selection = profilesEditor.getSelection();
for(Profile filter : selection) {
Command removeCommand = RemoveCommand.create(editingDomain, model.getProfiles(), //
POM_PACKAGE.getProfilesType_Profile(), filter);
compoundCommand.append(removeCommand);
}
editingDomain.getCommandStack().execute(compoundCommand);
}
});
profilesEditor.setCellModifier(new ICellModifier() {
public boolean canModify(Object element, String property) {
return true;
}
public Object getValue(Object element, String property) {
if(element instanceof Profile) {
String id = ((Profile) element).getId();
return isEmpty(id) ? "" : id;
}
return "";
}
public void modify(Object element, String property, Object value) {
int n = profilesEditor.getViewer().getTable().getSelectionIndex();
Profile profile = model.getProfiles().getProfile().get(n);
if(!value.equals(profile.getId())) {
EditingDomain editingDomain = getEditingDomain();
Command command = SetCommand.create(editingDomain, profile, POM_PACKAGE.getProfile_Id(), value);
editingDomain.getCommandStack().execute(command);
profilesEditor.refresh();
}
}
});
profilesEditor.setReadOnly(pomEditor.isReadOnly());
}
|
org.maven.ide.eclipse.editor/src/org/maven/ide/eclipse/editor/pom/ProfilesPage.java
|
satd-removal_data_70
|
TODO: Should re-factored as described in OPENNLP-193
public void run(String[] args) {
if (args.length < 8) {
System.out.println(getHelp());
throw new TerminateToolException(1);
}
TrainingParameters parameters = new TrainingParameters(args);
if(!parameters.isValid()) {
System.out.println(getHelp());
throw new TerminateToolException(1);
}
opennlp.tools.util.TrainingParameters mlParams =
CmdLineUtil.loadTrainingParameters(CmdLineUtil.getParameter("-params", args), true);
if (mlParams != null && !TrainUtil.isValid(mlParams.getSettings())) {
System.err.println("Training parameters file is invalid!");
throw new TerminateToolException(-1);
}
File trainingDataInFile = new File(CmdLineUtil.getParameter("-data", args));
File modelOutFile = new File(CmdLineUtil.getParameter("-model", args));
CmdLineUtil.checkOutputFile("pos tagger model", modelOutFile);
ObjectStream<POSSample> sampleStream = openSampleData("Training", trainingDataInFile,
parameters.getEncoding());
Dictionary ngramDict = null;
String ngramCutoffString = CmdLineUtil.getParameter("-ngram", args);
if (ngramCutoffString != null) {
System.err.print("Building ngram dictionary ... ");
int ngramCutoff = Integer.parseInt(ngramCutoffString);
try {
ngramDict = POSTaggerME.buildNGramDictionary(sampleStream, ngramCutoff);
sampleStream.reset();
} catch (IOException e) {
CmdLineUtil.printTrainingIoError(e);
throw new TerminateToolException(-1);
}
System.err.println("done");
}
POSModel model;
try {
// TODO: Move to util method ...
POSDictionary tagdict = null;
if (parameters.getDictionaryPath() != null) {
// TODO: Should re-factored as described in OPENNLP-193
tagdict = new POSDictionary(parameters.getDictionaryPath());
}
if (mlParams == null) {
// depending on model and sequence choose training method
model = opennlp.tools.postag.POSTaggerME.train(parameters.getLanguage(),
sampleStream, parameters.getModel(), tagdict, ngramDict, parameters.getCutoff(), parameters.getNumberOfIterations());
}
else {
model = opennlp.tools.postag.POSTaggerME.train(parameters.getLanguage(),
sampleStream, mlParams, tagdict, ngramDict);
}
}
catch (IOException e) {
CmdLineUtil.printTrainingIoError(e);
throw new TerminateToolException(-1);
}
finally {
try {
sampleStream.close();
} catch (IOException e) {
// sorry that this can fail
}
}
CmdLineUtil.writeModel("pos tagger", modelOutFile, model);
}
public void run(String[] args) {
if (!ArgumentParser.validateArguments(args, TrainerToolParams.class)) {
System.err.println(getHelp());
throw new TerminateToolException(1);
}
TrainerToolParams params = ArgumentParser.parse(args,
TrainerToolParams.class);
opennlp.tools.util.TrainingParameters mlParams =
CmdLineUtil.loadTrainingParameters(params.getParams(), true);
if (mlParams != null && !TrainUtil.isValid(mlParams.getSettings())) {
System.err.println("Training parameters file is invalid!");
throw new TerminateToolException(-1);
}
File trainingDataInFile = params.getData();
File modelOutFile = params.getModel();
CmdLineUtil.checkOutputFile("pos tagger model", modelOutFile);
ObjectStream<POSSample> sampleStream = openSampleData("Training", trainingDataInFile,
params.getEncoding());
Dictionary ngramDict = null;
Integer ngramCutoff = params.getNgram();
if (ngramCutoff != null) {
System.err.print("Building ngram dictionary ... ");
try {
ngramDict = POSTaggerME.buildNGramDictionary(sampleStream, ngramCutoff);
sampleStream.reset();
} catch (IOException e) {
CmdLineUtil.printTrainingIoError(e);
throw new TerminateToolException(-1);
}
System.err.println("done");
}
POSModel model;
try {
// TODO: Move to util method ...
POSDictionary tagdict = null;
if (params.getDict() != null) {
tagdict = POSDictionary.create(new FileInputStream(params.getDict()));
}
if (mlParams == null) {
// depending on model and sequence choose training method
model = opennlp.tools.postag.POSTaggerME.train(params.getLang(),
sampleStream, getModelType(params.getType()), tagdict, ngramDict, params.getCutoff(), params.getIterations());
}
else {
model = opennlp.tools.postag.POSTaggerME.train(params.getLang(),
sampleStream, mlParams, tagdict, ngramDict);
}
}
catch (IOException e) {
CmdLineUtil.printTrainingIoError(e);
throw new TerminateToolException(-1);
}
finally {
try {
sampleStream.close();
} catch (IOException e) {
// sorry that this can fail
}
}
CmdLineUtil.writeModel("pos tagger", modelOutFile, model);
}
|
opennlp-tools/src/main/java/opennlp/tools/cmdline/postag/POSTaggerTrainerTool.java
|
satd-removal_data_71
|
TODO: clear out the SyncState
private void modifyCalendarSubscription(long id, boolean syncEvents) {
// get the account, url, and current selected state
// for this calendar.
Cursor cursor = query(ContentUris.withAppendedId(Calendars.CONTENT_URI, id),
new String[] {Calendars._SYNC_ACCOUNT, Calendars._SYNC_ACCOUNT_TYPE,
Calendars.URL, Calendars.SYNC_EVENTS},
null /* selection */,
null /* selectionArgs */,
null /* sort */);
Account account = null;
String calendarUrl = null;
boolean oldSyncEvents = false;
if (cursor != null && cursor.moveToFirst()) {
try {
final String accountName = cursor.getString(0);
final String accountType = cursor.getString(1);
account = new Account(accountName, accountType);
calendarUrl = cursor.getString(2);
oldSyncEvents = (cursor.getInt(3) != 0);
} finally {
cursor.close();
}
}
if (account == null) {
// should not happen?
Log.w(TAG, "Cannot update subscription because account "
+ "is empty -- should not happen.");
return;
}
if (TextUtils.isEmpty(calendarUrl)) {
// Passing in a null Url will cause it to not add any extras
// Should only happen for non-google calendars.
calendarUrl = null;
}
if (oldSyncEvents == syncEvents) {
// nothing to do
return;
}
// If we are no longer syncing a calendar then make sure that the
// old calendar sync data is cleared. Then if we later add this
// calendar back, we will sync all the events.
if (!syncEvents) {
// TODO: clear out the SyncState
// byte[] data = readSyncDataBytes(account);
// GDataSyncData syncData = AbstractGDataSyncAdapter.newGDataSyncDataFromBytes(data);
// if (syncData != null) {
// syncData.feedData.remove(calendarUrl);
// data = AbstractGDataSyncAdapter.newBytesFromGDataSyncData(syncData);
// writeSyncDataBytes(account, data);
// }
// Delete all of the events in this calendar to save space.
// This is the closest we can come to deleting a calendar.
// Clients should never actually delete a calendar. That won't
// work. We need to keep the calendar entry in the Calendars table
// in order to know not to sync the events for that calendar from
// the server.
String[] args = new String[] {String.valueOf(id)};
mDb.delete("Events", CALENDAR_ID_SELECTION, args);
// TODO: cancel any pending/ongoing syncs for this calendar.
// TODO: there is a corner case to deal with here: namely, if
// we edit or delete an event on the phone and then remove
// (that is, stop syncing) a calendar, and if we also make a
// change on the server to that event at about the same time,
// then we will never propagate the changes from the phone to
// the server.
}
// If the calendar is not selected for syncing, then don't download
// events.
mDbHelper.scheduleSync(account, !syncEvents, calendarUrl);
}
private void modifyCalendarSubscription(long id, boolean syncEvents) {
// get the account, url, and current selected state
// for this calendar.
Cursor cursor = query(ContentUris.withAppendedId(Calendars.CONTENT_URI, id),
new String[] {Calendars._SYNC_ACCOUNT, Calendars._SYNC_ACCOUNT_TYPE,
Calendars.URL, Calendars.SYNC_EVENTS},
null /* selection */,
null /* selectionArgs */,
null /* sort */);
Account account = null;
String calendarUrl = null;
boolean oldSyncEvents = false;
if (cursor != null && cursor.moveToFirst()) {
try {
final String accountName = cursor.getString(0);
final String accountType = cursor.getString(1);
account = new Account(accountName, accountType);
calendarUrl = cursor.getString(2);
oldSyncEvents = (cursor.getInt(3) != 0);
} finally {
cursor.close();
}
}
if (account == null) {
// should not happen?
Log.w(TAG, "Cannot update subscription because account "
+ "is empty -- should not happen.");
return;
}
if (TextUtils.isEmpty(calendarUrl)) {
// Passing in a null Url will cause it to not add any extras
// Should only happen for non-google calendars.
calendarUrl = null;
}
if (oldSyncEvents == syncEvents) {
// nothing to do
return;
}
// If the calendar is not selected for syncing, then don't download
// events.
mDbHelper.scheduleSync(account, !syncEvents, calendarUrl);
}
|
src/com/android/providers/calendar/CalendarProvider2.java
|
satd-removal_data_72
|
TODO should support deletion of profile with children
public void deleteProfile(int profileId) {
// TODO should support deletion of profile with children
RulesProfile profile = getSession().getEntity(RulesProfile.class, profileId);
if (profile != null && !profile.getProvided()) {
String hql = "UPDATE " + ResourceModel.class.getSimpleName() + " o SET o.rulesProfile=null WHERE o.rulesProfile=:rulesProfile";
getSession().createQuery(hql).setParameter("rulesProfile", profile).executeUpdate();
getSession().remove(profile);
getSession().commit();
}
}
public void deleteProfile(int profileId) {
RulesProfile profile = getSession().getEntity(RulesProfile.class, profileId);
if (profile != null && !profile.getProvided() && getChildren(profile).isEmpty()) {
String hql = "UPDATE " + ResourceModel.class.getSimpleName() + " o SET o.rulesProfile=null WHERE o.rulesProfile=:rulesProfile";
getSession().createQuery(hql).setParameter("rulesProfile", profile).executeUpdate();
getSession().remove(profile);
getSession().commit();
}
}
|
sonar-server/src/main/java/org/sonar/server/configuration/ProfilesManager.java
|
satd-removal_data_73
|
FIXME check whether thread has been cancelled or not before refresh() and refreshAction.call()
void refresh() {
// FIXME check whether thread has been cancelled or not before refresh() and refreshAction.call()
// FIXME protect this call, or at least log some error
this.credentialsProvider.refresh();
Iterator<Registration> iterator = registrations.values().iterator();
while (iterator.hasNext()) {
Registration registration = iterator.next();
// FIXME set a timeout on the call? (needs a separate thread)
try {
boolean refreshed = registration.refreshAction.call();
if (!refreshed) {
LOGGER.debug("Registration did not refresh token");
iterator.remove();
}
registration.errorHistory.set(0);
} catch (Exception e) {
LOGGER.warn("Error while trying to refresh a connection token", e);
registration.errorHistory.incrementAndGet();
if (registration.errorHistory.get() >= 5) {
registrations.remove(registration.id);
}
}
}
}
void refresh() {
if (Thread.currentThread().isInterrupted()) {
return;
}
int attemptCount = 0;
boolean refreshSucceeded = false;
while (attemptCount < 3) {
LOGGER.debug("Refreshing token for credentials provider {}", credentialsProvider);
try {
this.credentialsProvider.refresh();
LOGGER.debug("Token refreshed for credentials provider {}", credentialsProvider);
refreshSucceeded = true;
break;
} catch (Exception e) {
LOGGER.warn("Error while trying to refresh token: {}", e.getMessage());
}
attemptCount++;
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
if (!refreshSucceeded) {
LOGGER.warn("Token refresh failed after retry, aborting callbacks");
return;
}
Iterator<Registration> iterator = registrations.values().iterator();
while (iterator.hasNext() && !Thread.currentThread().isInterrupted()) {
Registration registration = iterator.next();
// FIXME set a timeout on the call? (needs a separate thread)
try {
boolean refreshed = registration.refreshAction.call();
if (!refreshed) {
LOGGER.debug("Registration did not refresh token");
iterator.remove();
}
registration.errorHistory.set(0);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
LOGGER.warn("Error while trying to refresh a connection token", e);
registration.errorHistory.incrementAndGet();
if (registration.errorHistory.get() >= 5) {
registrations.remove(registration.id);
}
}
}
}
|
src/main/java/com/rabbitmq/client/impl/DefaultCredentialsRefreshService.java
|
satd-removal_data_74
|
TODO add in IProblem stuff here
protected void usingClause(IASTScope scope)
throws Backtrack
{
IToken firstToken = consume(IToken.t_using);
if (LT(1) == IToken.t_namespace)
{
// using-directive
consume(IToken.t_namespace);
// optional :: and nested classes handled in name
TokenDuple duple = null;
if (LT(1) == IToken.tIDENTIFIER || LT(1) == IToken.tCOLONCOLON)
duple = name();
else
throw backtrack;
if (LT(1) == IToken.tSEMI)
{
IToken last = consume(IToken.tSEMI);
IASTUsingDirective astUD = null;
try
{
astUD = astFactory.createUsingDirective(scope, duple, firstToken.getOffset(), last.getEndOffset());
}
catch (ASTSemanticException e)
{
//TODO add in IProblem stuff here
failParse();
}
astUD.acceptElement(requestor);
return;
}
else
{
throw backtrack;
}
}
else
{
boolean typeName = false;
if (LT(1) == IToken.t_typename)
{
typeName = true;
consume(IToken.t_typename);
}
TokenDuple name = null;
if (LT(1) == IToken.tIDENTIFIER || LT(1) == IToken.tCOLONCOLON)
{
// optional :: and nested classes handled in name
name = name();
}
else
{
throw backtrack;
}
if (LT(1) == IToken.tSEMI)
{
IToken last = consume(IToken.tSEMI);
IASTUsingDeclaration declaration = null;
try
{
declaration =
astFactory.createUsingDeclaration(
scope,
typeName,
name,
firstToken.getOffset(),
last.getEndOffset());
}
catch (ASTSemanticException e)
{
}
declaration.acceptElement( requestor );
}
else
{
throw backtrack;
}
}
}
protected void usingClause(IASTScope scope)
throws Backtrack
{
IToken firstToken = consume(IToken.t_using);
if (LT(1) == IToken.t_namespace)
{
// using-directive
consume(IToken.t_namespace);
// optional :: and nested classes handled in name
TokenDuple duple = null;
if (LT(1) == IToken.tIDENTIFIER || LT(1) == IToken.tCOLONCOLON)
duple = name();
else
throw backtrack;
if (LT(1) == IToken.tSEMI)
{
IToken last = consume(IToken.tSEMI);
IASTUsingDirective astUD = null;
try
{
astUD = astFactory.createUsingDirective(scope, duple, firstToken.getOffset(), last.getEndOffset());
}
catch (ASTSemanticException e)
{
failParse();
throw backtrack;
}
astUD.acceptElement(requestor);
return;
}
else
{
throw backtrack;
}
}
else
{
boolean typeName = false;
if (LT(1) == IToken.t_typename)
{
typeName = true;
consume(IToken.t_typename);
}
TokenDuple name = null;
if (LT(1) == IToken.tIDENTIFIER || LT(1) == IToken.tCOLONCOLON)
{
// optional :: and nested classes handled in name
name = name();
}
else
{
throw backtrack;
}
if (LT(1) == IToken.tSEMI)
{
IToken last = consume(IToken.tSEMI);
IASTUsingDeclaration declaration = null;
try
{
declaration =
astFactory.createUsingDeclaration(
scope,
typeName,
name,
firstToken.getOffset(),
last.getEndOffset());
}
catch (ASTSemanticException e)
{
failParse();
throw backtrack;
}
declaration.acceptElement( requestor );
}
else
{
throw backtrack;
}
}
}
|
core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/parser/Parser.java
|
satd-removal_data_75
|
TODO: NPE once occurred on line below.
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void payForAction(FactionsEventMembershipChange event)
{
Double cost = null;
String desc = null;
if (event.getReason() == MembershipChangeReason.JOIN)
{
cost = UConf.get(event.getSender()).econCostJoin;
desc = "join a faction";
}
else if (event.getReason() == MembershipChangeReason.LEAVE)
{
// TODO: NPE once occurred on line below.
cost = UConf.get(event.getSender()).econCostLeave;
desc = "leave a faction";
}
else if (event.getReason() == MembershipChangeReason.KICK)
{
cost = UConf.get(event.getSender()).econCostKick;
desc = "kick someone from a faction";
}
else
{
return;
}
payForAction(event, cost, desc);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void payForAction(FactionsEventMembershipChange event)
{
Double cost = null;
String desc = null;
UConf uconf = UConf.get(event.getSender());
if (uconf == null) return;
if (event.getReason() == MembershipChangeReason.JOIN)
{
cost = uconf.econCostJoin;
desc = "join a faction";
}
else if (event.getReason() == MembershipChangeReason.LEAVE)
{
cost = uconf.econCostLeave;
desc = "leave a faction";
}
else if (event.getReason() == MembershipChangeReason.KICK)
{
cost = uconf.econCostKick;
desc = "kick someone from a faction";
}
else
{
return;
}
payForAction(event, cost, desc);
}
|
src/com/massivecraft/factions/listeners/FactionsListenerEcon.java
|
satd-removal_data_76
|
TODO: add code here
@Override
public void addGenotypeCall(GenotypeCall locus) {
// TODO: add code here
}
@Override
public void addGenotypeCall(GenotypeOutput locus) {
SSGGenotypeCall call = (SSGGenotypeCall)locus;
LikelihoodObject obj = new LikelihoodObject(call.getLikelihoods(), LikelihoodObject.LIKELIHOOD_TYPE.LOG);
this.addGenotypeCall(GenomeLocParser.getContigInfo(locus.getLocation().getContig()),(int)locus.getLocation().getStart(),(float)locus.getRmsMapping(),locus.getReferencebase(),locus.getReadDepth(),obj);
}
|
java/src/org/broadinstitute/sting/utils/genotype/geli/GeliAdapter.java
|
satd-removal_data_77
|
TODO Use wildcard constructor once BV API is updated (BVAL-358)
@Test
@SpecAssertion(section = "4.5.2", id = "a")
public void testConstructorParameterConstraintsAreDeclaredByAnnotingParameters()
throws Exception {
//TODO Use wildcard constructor once BV API is updated (BVAL-358)
//Constructor<?> constructor = getParameterConstrainedConstructor();
Constructor constructor = CalendarService.class.getConstructor( String.class );
Object[] parameterValues = new Object[1];
Set<ConstraintViolation<Object>> constraintViolations = executableValidator.validateConstructorParameters(
constructor,
parameterValues
);
assertNotNull( constraintViolations );
assertCorrectNumberOfViolations( constraintViolations, 1 );
assertCorrectConstraintTypes( constraintViolations, NotNull.class );
}
@Test
@SpecAssertion(section = "4.5.2", id = "a")
public void testConstructorParameterConstraintsAreDeclaredByAnnotingParameters()
throws Exception {
Constructor<?> constructor = CalendarService.class.getConstructor( String.class );
Object[] parameterValues = new Object[1];
Set<ConstraintViolation<Object>> constraintViolations = executableValidator.validateConstructorParameters(
constructor,
parameterValues
);
assertNotNull( constraintViolations );
assertCorrectNumberOfViolations( constraintViolations, 1 );
assertCorrectConstraintTypes( constraintViolations, NotNull.class );
}
|
tests/src/main/java/org/hibernate/beanvalidation/tck/tests/constraints/application/method/MethodValidationRequirementTest.java
|
satd-removal_data_78
|
@todo Use WagonManager#getWagon(Repository) when available. It's available in Maven 2.0.5.
public void execute()
throws MojoExecutionException
{
if ( !inputDirectory.exists() )
{
throw new MojoExecutionException( "The site does not exist, please run site:site first" );
}
DistributionManagement distributionManagement = project.getDistributionManagement();
if ( distributionManagement == null )
{
throw new MojoExecutionException( "Missing distribution management information in the project" );
}
Site site = distributionManagement.getSite();
if ( site == null )
{
throw new MojoExecutionException(
"Missing site information in the distribution management element in the project.." );
}
String url = site.getUrl();
String id = site.getId();
if ( url == null )
{
throw new MojoExecutionException( "The URL to the site is missing in the project descriptor." );
}
Repository repository = new Repository( id, url );
// TODO: work on moving this into the deployer like the other deploy methods
Wagon wagon;
try
{
// @todo Use WagonManager#getWagon(Repository) when available. It's available in Maven 2.0.5.
wagon = wagonManager.getWagon( repository.getProtocol() );
configureWagon( wagon, repository.getId(), settings, container, getLog() );
}
catch ( UnsupportedProtocolException e )
{
throw new MojoExecutionException( "Unsupported protocol: '" + repository.getProtocol() + "'", e );
}
catch ( WagonConfigurationException e )
{
throw new MojoExecutionException( "Unable to configure Wagon: '" + repository.getProtocol() + "'", e );
}
if ( !wagon.supportsDirectoryCopy() )
{
throw new MojoExecutionException(
"Wagon protocol '" + repository.getProtocol() + "' doesn't support directory copying" );
}
try
{
Debug debug = new Debug();
wagon.addSessionListener( debug );
wagon.addTransferListener( debug );
ProxyInfo proxyInfo = getProxyInfo( repository, wagonManager );
if ( proxyInfo != null )
{
wagon.connect( repository, wagonManager.getAuthenticationInfo( id ), proxyInfo );
}
else
{
wagon.connect( repository, wagonManager.getAuthenticationInfo( id ) );
}
wagon.putDirectory( inputDirectory, "." );
// TODO: current wagon uses zip which will use the umask on remote host instead of honouring our settings
// Force group writeable
if ( wagon instanceof CommandExecutor )
{
CommandExecutor exec = (CommandExecutor) wagon;
exec.executeCommand( "chmod -Rf g+w,a+rX " + repository.getBasedir() );
}
}
catch ( ResourceDoesNotExistException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( TransferFailedException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( AuthorizationException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( ConnectionException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( AuthenticationException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( CommandExecutionException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
finally
{
try
{
wagon.disconnect();
}
catch ( ConnectionException e )
{
getLog().error( "Error disconnecting wagon - ignored", e );
}
}
}
public void execute()
throws MojoExecutionException
{
if ( !inputDirectory.exists() )
{
throw new MojoExecutionException( "The site does not exist, please run site:site first" );
}
DistributionManagement distributionManagement = project.getDistributionManagement();
if ( distributionManagement == null )
{
throw new MojoExecutionException( "Missing distribution management information in the project" );
}
Site site = distributionManagement.getSite();
if ( site == null )
{
throw new MojoExecutionException(
"Missing site information in the distribution management element in the project.." );
}
String url = site.getUrl();
String id = site.getId();
if ( url == null )
{
throw new MojoExecutionException( "The URL to the site is missing in the project descriptor." );
}
Repository repository = new Repository( id, url );
// TODO: work on moving this into the deployer like the other deploy methods
Wagon wagon;
try
{
wagon = wagonManager.getWagon( repository );
configureWagon( wagon, repository.getId(), settings, container, getLog() );
}
catch ( UnsupportedProtocolException e )
{
throw new MojoExecutionException( "Unsupported protocol: '" + repository.getProtocol() + "'", e );
}
catch ( WagonConfigurationException e )
{
throw new MojoExecutionException( "Unable to configure Wagon: '" + repository.getProtocol() + "'", e );
}
if ( !wagon.supportsDirectoryCopy() )
{
throw new MojoExecutionException(
"Wagon protocol '" + repository.getProtocol() + "' doesn't support directory copying" );
}
try
{
Debug debug = new Debug();
wagon.addSessionListener( debug );
wagon.addTransferListener( debug );
ProxyInfo proxyInfo = getProxyInfo( repository, wagonManager );
if ( proxyInfo != null )
{
wagon.connect( repository, wagonManager.getAuthenticationInfo( id ), proxyInfo );
}
else
{
wagon.connect( repository, wagonManager.getAuthenticationInfo( id ) );
}
wagon.putDirectory( inputDirectory, "." );
// TODO: current wagon uses zip which will use the umask on remote host instead of honouring our settings
// Force group writeable
if ( wagon instanceof CommandExecutor )
{
CommandExecutor exec = (CommandExecutor) wagon;
exec.executeCommand( "chmod -Rf g+w,a+rX " + repository.getBasedir() );
}
}
catch ( ResourceDoesNotExistException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( TransferFailedException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( AuthorizationException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( ConnectionException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( AuthenticationException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
catch ( CommandExecutionException e )
{
throw new MojoExecutionException( "Error uploading site", e );
}
finally
{
try
{
wagon.disconnect();
}
catch ( ConnectionException e )
{
getLog().error( "Error disconnecting wagon - ignored", e );
}
}
}
|
maven-site-plugin/src/main/java/org/apache/maven/plugins/site/SiteDeployMojo.java
|
satd-removal_data_79
|
TODO: Handle context flags
public static CommandSpec getOptionCommand(PermissionsEx pex) {
return CommandSpec.builder()
.setAliases("options", "option", "opt", "o")
.setArguments(seq(string(_("key")), optional(string(_("val")))))
.setExecutor(new PermissionsExExecutor(pex) {
@Override
public <TextType> void execute(Commander<TextType> src, CommandContext args) throws CommandException {
Map.Entry<String, String> subject = subjectOrSelf(src, args);
checkSubjectPermission(src, subject, "permissionsex.option.set");
Set<Map.Entry<String, String>> contexts = GLOBAL; // TODO: Handle context flags
SubjectCache dataCache = args.hasAny("transient") ? pex.getTransientSubjects(subject.getKey()) : pex.getSubjects(subject.getKey());
ImmutableOptionSubjectData data = getSubjectData(dataCache, subject.getValue());
final String key = args.getOne("key");
final String value = args.getOne("value");
if (value == null) {
messageSubjectOnFuture(
dataCache.update(subject.getValue(), data.setOption(contexts, key, null)), src,
_("Unset option '%s' for subject %s in %s context", key, src.fmt().hl(src.fmt().subject(subject)), formatContexts(src, contexts)));
} else {
messageSubjectOnFuture(
dataCache.update(subject.getValue(), data.setOption(contexts, key, value)), src,
_("Set option %s for subject %s in %s context", src.fmt().option(key, value), src.fmt().hl(src.fmt().subject(subject)), formatContexts(src, contexts)));
}
}
})
.build();
}
public static CommandSpec getOptionCommand(PermissionsEx pex) {
return CommandSpec.builder()
.setAliases("options", "option", "opt", "o")
.setArguments(seq(string(_("key")), optional(string(_("val")))))
.setExecutor(new PermissionsExExecutor(pex) {
@Override
public <TextType> void execute(Commander<TextType> src, CommandContext args) throws CommandException {
Map.Entry<String, String> subject = subjectOrSelf(src, args);
checkSubjectPermission(src, subject, "permissionsex.option.set");
Set<Map.Entry<String, String>> contexts = ImmutableSet.copyOf(args.<Map.Entry<String, String>>getAll("context"));
SubjectCache dataCache = args.hasAny("transient") ? pex.getTransientSubjects(subject.getKey()) : pex.getSubjects(subject.getKey());
ImmutableOptionSubjectData data = getSubjectData(dataCache, subject.getValue());
final String key = args.getOne("key");
final String value = args.getOne("value");
if (value == null) {
messageSubjectOnFuture(
dataCache.update(subject.getValue(), data.setOption(contexts, key, null)), src,
_("Unset option '%s' for subject %s in %s context", key, src.fmt().hl(src.fmt().subject(subject)), formatContexts(src, contexts)));
} else {
messageSubjectOnFuture(
dataCache.update(subject.getValue(), data.setOption(contexts, key, value)), src,
_("Set option %s for subject %s in %s context", src.fmt().option(key, value), src.fmt().hl(src.fmt().subject(subject)), formatContexts(src, contexts)));
}
}
})
.build();
}
|
src/main/java/ninja/leaping/permissionsex/command/OptionCommands.java
|
satd-removal_data_80
|
TODO: Add to poison queue
private void startProcessor(final int id) {
executor.submit(new Runnable() {
@Override
public void run() {
String name = StringUtils.join(Lists.newArrayList(messageQueue.getName(), "Processor", Integer.toString(id)), ":");
Thread.currentThread().setName(name);
LOG.info("Starting message processor : " + name);
try {
while (!terminate) {
Message message = null;
try {
message = toProcess.take();
if (message == null)
continue;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
try {
LOG.debug(message.toString());
if (message.getTaskClass() != null) {
@SuppressWarnings("unchecked")
Function<Message, Boolean> task = (Function<Message, Boolean>)Class.forName(message.getTaskClass()).newInstance();
if (task.apply(message)) {
toAck.add(message);
}
continue;
}
if (callback.apply(message)) {
toAck.add(message);
continue;
}
}
catch (Throwable t) {
try {
ackConsumer.ackPoisonMessage(message);
} catch (MessageQueueException e) {
LOG.warn("Failed to ack poison message", e);
}
// TODO: Add to poison queue
LOG.error("Error processing message " + message.getKey(), t);
}
}
}
catch (Throwable t) {
LOG.error("Error running producer : " + name, t);
}
}
});
}
private void startProcessor(final int id) {
executor.submit(new Runnable() {
@Override
public void run() {
String name = StringUtils.join(Lists.newArrayList(messageQueue.getName(), "Processor", Integer.toString(id)), ":");
Thread.currentThread().setName(name);
LOG.info("Starting message processor : " + name);
try {
while (!terminate) {
// Pop a message off the queue
final MessageContext context;
try {
context = toProcess.take();
if (context == null)
continue;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
// Process the message
Message message = context.getMessage();
try {
// Message has a specific handler class
if (message.getTaskClass() != null) {
@SuppressWarnings("unchecked")
Function<MessageContext, Boolean> task = (Function<MessageContext, Boolean>)Class.forName(message.getTaskClass()).newInstance();
if (task.apply(context)) {
toAck.add(context);
}
continue;
}
// Use default callback
if (callback.apply(context)) {
context.setStatus(MessageStatus.DONE);
toAck.add(context);
continue;
}
}
catch (Throwable t) {
context.setException(t);
toAck.add(context);
LOG.error("Error processing message " + message.getKey(), t);
// try {
// ackConsumer.ackPoisonMessage(context);
// } catch (MessageQueueException e) {
// LOG.warn("Failed to ack poison message " + message.getKey(), e);
// }
}
}
}
catch (Throwable t) {
LOG.error("Error running producer : " + name, t);
}
}
});
}
|
src/main/java/com/netflix/astyanax/recipes/queue/MessageQueueDispatcher.java
|
satd-removal_data_81
|
TODO replace this with Imps.ProviderSettings.QueryMap settings.getUseTor()
void signIn() {
Intent intent = new Intent(MainActivity.this, SigningInActivity.class);
intent.setData(mAccountUri);
intent.putExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, mProviderId);
intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, mAccountId);
// TODO replace this with Imps.ProviderSettings.QueryMap settings.getUseTor()
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication());
boolean useTor = prefs.getBoolean("pref_security_use_tor", false);
if (useTor) {
// TODO move ImApp.EXTRA_INTENT_PROXY_* to ImServiceConstants
intent.putExtra(ImApp.EXTRA_INTENT_PROXY_TYPE,"SOCKS5");
intent.putExtra(ImApp.EXTRA_INTENT_PROXY_HOST,"127.0.0.1");
intent.putExtra(ImApp.EXTRA_INTENT_PROXY_PORT,9050);
}
// if (mToAddress != null) {
// intent.putExtra(ImApp.EXTRA_INTENT_SEND_TO_USER, mToAddress);
//}
startActivityForResult(intent, REQUEST_SIGN_IN);
}
void signIn() {
Intent intent = new Intent(MainActivity.this, SigningInActivity.class);
intent.setData(mAccountUri);
intent.putExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, mProviderId);
intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, mAccountId);
Imps.ProviderSettings.QueryMap settings = new Imps.ProviderSettings.QueryMap(
getContentResolver(), mProviderId,
false /* keep updated */, null /* no handler */);
if (settings.getUseTor()) {
intent.putExtra(ImApp.EXTRA_INTENT_PROXY_TYPE,"SOCKS5");
intent.putExtra(ImApp.EXTRA_INTENT_PROXY_HOST,"127.0.0.1");
intent.putExtra(ImApp.EXTRA_INTENT_PROXY_PORT,9050);
}
settings.close();
// if (mToAddress != null) {
// intent.putExtra(ImApp.EXTRA_INTENT_SEND_TO_USER, mToAddress);
//}
startActivityForResult(intent, REQUEST_SIGN_IN);
}
|
src/info/guardianproject/otr/app/im/ui/MainActivity.java
|
satd-removal_data_82
|
TODO Add scope check
@Test
public void testBrokenScope()
{
WebBeansConfigurationException result = null;
try
{
defineEjbBean(Babus_Broken.class);
}
catch (WebBeansConfigurationException e)
{
result = e;
}
//TODO Add scope check
Assert.assertNull(result);
}
@Test
public void testBrokenScope()
{
WebBeansConfigurationException result = null;
try
{
defineEjbBean(Babus_Broken.class);
}
catch (WebBeansConfigurationException e)
{
result = e;
}
Assert.assertNotNull(result);
}
|
webbeans-ejb/src/test/java/org/apache/webbeans/ejb/definition/scope/EjbScopeTypeTest.java
|
satd-removal_data_83
|
TODO: display result?
private void createQueue(final Shell parent)
{
final Shell shell = ViewUtility.createModalDialogShell(parent, "Create Queue");
Composite nameComposite = _toolkit.createComposite(shell, SWT.NONE);
nameComposite.setBackground(shell.getBackground());
nameComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
nameComposite.setLayout(new GridLayout(2,false));
_toolkit.createLabel(nameComposite,"Name:").setBackground(shell.getBackground());
final Text nameText = new Text(nameComposite, SWT.BORDER);
nameText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
Composite ownerComposite = _toolkit.createComposite(shell, SWT.NONE);
ownerComposite.setBackground(shell.getBackground());
ownerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
ownerComposite.setLayout(new GridLayout(2,false));
_toolkit.createLabel(ownerComposite,"Owner (optional):").setBackground(shell.getBackground());
final Text ownerText = new Text(ownerComposite, SWT.BORDER);
ownerText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
Composite durableComposite = _toolkit.createComposite(shell, SWT.NONE);
durableComposite.setBackground(shell.getBackground());
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.minimumWidth = 220;
durableComposite.setLayoutData(gridData);
durableComposite.setLayout(new GridLayout(2,false));
_toolkit.createLabel(durableComposite,"Durable:").setBackground(shell.getBackground());
final Button durableButton = new Button(durableComposite, SWT.CHECK);
durableButton.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false));
Composite okCancelButtonsComp = _toolkit.createComposite(shell);
okCancelButtonsComp.setBackground(shell.getBackground());
okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
okCancelButtonsComp.setLayout(new GridLayout(2,false));
Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
okButton.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
String name = nameText.getText();
if (name == null || name.length() == 0)
{
ViewUtility.popupErrorMessage("Create Queue", "Please enter a valid name");
return;
}
String owner = ownerText.getText();
if (owner != null && owner.length() == 0)
{
owner = null;
}
boolean durable = durableButton.getSelection();
shell.dispose();
try
{
_vhmb.createNewQueue(name, owner, durable);
//TODO: display result?
try
{
//delay to allow mbean registration notification processing
Thread.sleep(250);
}
catch(InterruptedException ie)
{
//ignore
}
}
catch(Exception e5)
{
MBeanUtility.handleException(_mbean, e5);
}
refresh(_mbean);
}
});
cancelButton.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
shell.dispose();
}
});
shell.setDefaultButton(okButton);
shell.pack();
shell.open();
}
private void createQueue(final Shell parent)
{
final Shell shell = ViewUtility.createModalDialogShell(parent, "Create Queue");
Composite nameComposite = _toolkit.createComposite(shell, SWT.NONE);
nameComposite.setBackground(shell.getBackground());
nameComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
nameComposite.setLayout(new GridLayout(2,false));
_toolkit.createLabel(nameComposite,"Name:").setBackground(shell.getBackground());
final Text nameText = new Text(nameComposite, SWT.BORDER);
nameText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
Composite ownerComposite = _toolkit.createComposite(shell, SWT.NONE);
ownerComposite.setBackground(shell.getBackground());
ownerComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
ownerComposite.setLayout(new GridLayout(2,false));
_toolkit.createLabel(ownerComposite,"Owner (optional):").setBackground(shell.getBackground());
final Text ownerText = new Text(ownerComposite, SWT.BORDER);
ownerText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
Composite durableComposite = _toolkit.createComposite(shell, SWT.NONE);
durableComposite.setBackground(shell.getBackground());
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.minimumWidth = 220;
durableComposite.setLayoutData(gridData);
durableComposite.setLayout(new GridLayout(2,false));
_toolkit.createLabel(durableComposite,"Durable:").setBackground(shell.getBackground());
final Button durableButton = new Button(durableComposite, SWT.CHECK);
durableButton.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false));
Composite okCancelButtonsComp = _toolkit.createComposite(shell);
okCancelButtonsComp.setBackground(shell.getBackground());
okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
okCancelButtonsComp.setLayout(new GridLayout(2,false));
Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
okButton.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
String name = nameText.getText();
if (name == null || name.length() == 0)
{
ViewUtility.popupErrorMessage("Create Queue", "Please enter a valid name");
return;
}
String owner = ownerText.getText();
if (owner != null && owner.length() == 0)
{
owner = null;
}
boolean durable = durableButton.getSelection();
shell.dispose();
try
{
_vhmb.createNewQueue(name, owner, durable);
ViewUtility.operationResultFeedback(null, "Created Queue", null);
try
{
//delay to allow mbean registration notification processing
Thread.sleep(250);
}
catch(InterruptedException ie)
{
//ignore
}
}
catch(Exception e5)
{
ViewUtility.operationFailedStatusBarMessage("Error creating Queue");
MBeanUtility.handleException(_mbean, e5);
}
refresh(_mbean);
}
});
cancelButton.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
shell.dispose();
}
});
shell.setDefaultButton(okButton);
shell.pack();
shell.open();
}
|
qpid/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/vhost/VHostTabControl.java
|
satd-removal_data_84
|
TODO: Created is put into the bread crumb as well, so this check fails.
public void testFilterWithData() {
final JobConfigHistory jch = hudson.getPlugin(JobConfigHistory.class);
jch.setSaveSystemConfiguration(true);
//create some config history data
try {
final FreeStyleProject project = createFreeStyleProject("Test1");
Thread.sleep(SLEEP_TIME);
project.disable();
Thread.sleep(SLEEP_TIME);
hudson.setSystemMessage("Testmessage");
Thread.sleep(SLEEP_TIME);
final FreeStyleProject secondProject = createFreeStyleProject("Test2");
Thread.sleep(SLEEP_TIME);
secondProject.delete();
} catch (Exception ex) {
fail("Unable to prepare Hudson instance: " + ex);
}
try {
checkSystemPage(webClient.goTo(JobConfigHistoryConsts.URLNAME));
checkSystemPage(webClient.goTo(JobConfigHistoryConsts.URLNAME + "/?filter=system"));
final HtmlPage htmlPageJobs = webClient.goTo(JobConfigHistoryConsts.URLNAME + "/?filter=jobs");
assertTrue("Verify history entry for job is listed.", htmlPageJobs.getAnchorByText("Test1") != null);
assertTrue("Verify history entry for deleted job is listed.",
htmlPageJobs.asText().contains(JobConfigHistoryConsts.DELETED_MARKER));
assertFalse("Verify that no history entry for system change is listed.",
htmlPageJobs.asText().contains("config (system)"));
assertTrue("Check link to job page.", htmlPageJobs.asXml().contains("job/Test1/" + JobConfigHistoryConsts.URLNAME));
final HtmlPage htmlPageDeleted = webClient.goTo("jobConfigHistory/?filter=deleted");
final String page = htmlPageDeleted.asXml();
assertTrue("Verify history entry for deleted job is listed.", page.contains(JobConfigHistoryConsts.DELETED_MARKER));
assertFalse("Verify no history entry for job is listed.", page.contains("Test1"));
assertFalse("Verify no history entry for system change is listed.", page.contains("(system)"));
assertTrue("Check link to historypage exists.", page.contains("history?name"));
// TODO: Created is put into the bread crumb as well, so this check fails.
//assertFalse("Verify that only \'Deleted\' entries are listed.", page.contains("Created") || page.contains("Changed"));
} catch (Exception ex) {
fail("Unable to complete testFilterWithData: " + ex);
}
}
public void testFilterWithData() {
final JobConfigHistory jch = hudson.getPlugin(JobConfigHistory.class);
jch.setSaveSystemConfiguration(true);
//create some config history data
try {
final FreeStyleProject project = createFreeStyleProject("Test1");
Thread.sleep(SLEEP_TIME);
project.disable();
Thread.sleep(SLEEP_TIME);
hudson.setSystemMessage("Testmessage");
Thread.sleep(SLEEP_TIME);
final FreeStyleProject secondProject = createFreeStyleProject("Test2");
Thread.sleep(SLEEP_TIME);
secondProject.delete();
} catch (Exception ex) {
fail("Unable to prepare Hudson instance: " + ex);
}
try {
checkSystemPage(webClient.goTo(JobConfigHistoryConsts.URLNAME));
checkSystemPage(webClient.goTo(JobConfigHistoryConsts.URLNAME + "/?filter=system"));
final HtmlPage htmlPageJobs = webClient.goTo(JobConfigHistoryConsts.URLNAME + "/?filter=jobs");
assertTrue("Verify history entry for job is listed.", htmlPageJobs.getAnchorByText("Test1") != null);
assertTrue("Verify history entry for deleted job is listed.",
htmlPageJobs.asText().contains(JobConfigHistoryConsts.DELETED_MARKER));
assertFalse("Verify that no history entry for system change is listed.",
htmlPageJobs.asText().contains("config (system)"));
assertTrue("Check link to job page.", htmlPageJobs.asXml().contains("job/Test1/" + JobConfigHistoryConsts.URLNAME));
final HtmlPage htmlPageDeleted = webClient.goTo("jobConfigHistory/?filter=deleted");
final String page = htmlPageDeleted.asXml();
assertTrue("Verify history entry for deleted job is listed.", page.contains(JobConfigHistoryConsts.DELETED_MARKER));
assertFalse("Verify no history entry for job is listed.", page.contains("Test1"));
assertFalse("Verify no history entry for system change is listed.", page.contains("(system)"));
assertTrue("Check link to historypage exists.", page.contains("history?name"));
assertFalse("Verify that only \'Deleted\' entries are listed.", page.contains("Created</td>") || page.contains("Changed</td>"));
} catch (Exception ex) {
fail("Unable to complete testFilterWithData: " + ex);
}
}
|
src/test/java/hudson/plugins/jobConfigHistory/JobConfigHistoryRootActionIT.java
|
satd-removal_data_85
|
TODO: Remove this hard-coded value when the GadgetInfo is real.
void addGadgetView(int gadgetId, GadgetInfo gadget) {
// TODO: Remove this hard-coded value when the GadgetInfo is real.
gadget.initialLayout = R.layout.test_gadget;
// Inflate the gadget's RemoteViews
GadgetHostView view = mHost.createView(this, gadgetId, gadget);
// Add it to the list
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
65, // LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mGadgetContainer.addView(view, layoutParams);
}
void addGadgetView(int gadgetId, GadgetInfo gadget) {
// Inflate the gadget's RemoteViews
GadgetHostView view = mHost.createView(this, gadgetId, gadget);
// Add it to the list
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
65, // LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mGadgetContainer.addView(view, layoutParams);
}
|
tests/GadgetHost/src/com/android/gadgethost/GadgetHostActivity.java
|
satd-removal_data_86
|
TODO remove, as long as bnd does not support the multiple entries on sourcepath
@Override
public void validateProject(Project model) throws Exception {
//
// We must have, a project and assume this is already reported
//
if (model == null) {
return;
}
IJavaProject javaProject = Central.getJavaProject(model);
if (javaProject == null) {
model.error("Eclipse: The project in %s is not linked with a Java project.", model.getBase());
return;
}
//
// Verify if we have the right relation to the cnf folder ...
//
Project w = Workspace.getProject(model.getBase());
if (w == null || w != model) {
model.error("Eclipse: Error in setup, likely the cnf folder is not ../cnf relative from the project folder %s. The workspace is in %s", model.getBase(), model.getWorkspace().getBase());
return;
}
//
// Get the different bnd directories ...
//
File bin = model.getOutput();
File test = model.getTestSrc();
File bin_test = model.getTestOutput();
Set<File> sourcePath = new HashSet<File>(model.getSourcePath());
// TODO remove, as long as bnd does not support the multiple entries on sourcepath
if (sourcePath.size() == 1 && sourcePath.iterator().next().equals(model.getBase()))
return;
//
// All the things we should find when we have traversed the build path
//
Set<SetupTypes> found = new HashSet<SetupTypes>(EnumSet.allOf(SetupTypes.class));
for (IClasspathEntry cpe : javaProject.getRawClasspath()) {
int kind = cpe.getEntryKind();
switch (kind) {
case IClasspathEntry.CPE_VARIABLE :
warning(model, null, null, cpe, "Eclipse: Found a variable in the eclipse build path, this variable is not available during continuous integration", cpe).file(new File(model.getBase(), ".classpath").getAbsolutePath());
;
break;
case IClasspathEntry.CPE_CONTAINER :
if (BndtoolsConstants.BND_CLASSPATH_ID.segment(0).equals(cpe.getPath().segment(0)))
found.remove(SetupTypes.bndcontainer);
else {
// warning because default might vary <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
// check javac version <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
// warnig because local/machine specific <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.launching.macosx.MacOSXType/Java SE 7 [1.7.0_71]"/>
}
break;
case IClasspathEntry.CPE_SOURCE :
File file = toFile(cpe.getPath());
if (file == null) {
model.warning("Eclipse: Found virtual file for %s", cpe).details(cpe);
} else {
File output = toFile(cpe.getOutputLocation());
if (output == null)
output = toFile(javaProject.getOutputLocation());
if (file.equals(test)) {
//
// We're talking about the test source directory
// This should be linked to bin_test
//
found.remove(SetupTypes.test);
if (bin_test.equals(output)) {
found.remove(SetupTypes.bin_test);
} else
warning(model, DEFAULT_PROP_TESTBIN_DIR, bin_test, cpe, "Eclipse: Source test folder %s has output set to %s, which does not match bnd's bin_test folder %s", file, output, bin_test);
} else {
//
// We must have a source directory. They must be linked to the bin
// folder and on the bnd source path. Since the source path has
// potentially multiple entries, we remove this one so we can check
// later if we had all of them
//
if (sourcePath.remove(file)) {
if (bin.equals(output)) {
found.remove(SetupTypes.bin);
} else
warning(model, DEFAULT_PROP_BIN_DIR, bin, cpe, "Eclipse: Source folder %s has output set to %s, \n" + "which does not match bnd's bin folder %s", file, output, bin_test);
} else {
warning(model, DEFAULT_PROP_SRC_DIR, null, cpe, "Eclipse: Found source folder %s that is not on the source path %s", file, model.getSourcePath());
}
}
}
break;
case IClasspathEntry.CPE_LIBRARY :
warning(model, null, null, cpe, "Eclipse: The .classpath containsa direct library that will not be available during continuous integration: %s", cpe.getPath()).file(new File(model.getBase(), ".classpath").getAbsolutePath());
break;
default :
break;
}
}
//
// If we had not see all source entries, then we should
// have something in sourcePath
//
for (File f : sourcePath) {
warning(model, DEFAULT_PROP_SRC_DIR, f, null, "Eclipse: Source directory '%s' defined in bnd and not on the Eclipse build path", f);
}
//
// Check if we had all the different things we needed to check
//
for (SetupTypes t : found) {
switch (t) {
case bin :
warning(model, DEFAULT_PROP_BIN_DIR, null, null, "Eclipse: No entry on the build path uses the bnd bin directory %s", bin);
break;
case bin_test :
warning(model, DEFAULT_PROP_TESTBIN_DIR, null, null, "Eclipse: No entry on the build path uses the bnd bin_test directory %s", bin_test);
break;
case bndcontainer :
warning(model, null, null, null, "Eclipse: The build path does not refer to a bnd container");
break;
case test :
warning(model, DEFAULT_PROP_TESTSRC_DIR, null, null, "Eclipse: No test folder %s found", test);
break;
default :
break;
}
}
}
@Override
public void validateProject(Project model) throws Exception {
//
// We must have, a project and assume this is already reported
//
if (model == null) {
return;
}
IJavaProject javaProject = Central.getJavaProject(model);
if (javaProject == null) {
model.error("Eclipse: The project in %s is not linked with a Java project.", model.getBase());
return;
}
//
// Verify if we have the right relation to the cnf folder ...
//
Project w = Workspace.getProject(model.getBase());
if (w == null || w != model) {
model.error("Eclipse: Error in setup, likely the cnf folder is not ../cnf relative from the project folder %s. The workspace is in %s", model.getBase(), model.getWorkspace().getBase());
return;
}
//
// Get the different bnd directories ...
//
File bin = model.getOutput();
File test = model.getTestSrc();
File bin_test = model.getTestOutput();
Set<File> sourcePath = new HashSet<File>(model.getSourcePath());
//
// All the things we should find when we have traversed the build path
//
Set<SetupTypes> found = new HashSet<SetupTypes>(EnumSet.allOf(SetupTypes.class));
for (IClasspathEntry cpe : javaProject.getRawClasspath()) {
int kind = cpe.getEntryKind();
switch (kind) {
case IClasspathEntry.CPE_VARIABLE :
warning(model, null, null, cpe, "Eclipse: Found a variable in the eclipse build path, this variable is not available during continuous integration", cpe).file(new File(model.getBase(), ".classpath").getAbsolutePath());
break;
case IClasspathEntry.CPE_LIBRARY :
warning(model, null, null, cpe, "Eclipse: The .classpath containsa a library that will not be available during continuous integration: %s", cpe.getPath()).file(new File(model.getBase(), ".classpath").getAbsolutePath());
break;
case IClasspathEntry.CPE_CONTAINER :
if (BndtoolsConstants.BND_CLASSPATH_ID.segment(0).equals(cpe.getPath().segment(0)))
found.remove(SetupTypes.bndcontainer);
else {
IPath path = cpe.getPath();
if (JRE_CONTAINER.segment(0).equals(path.segment(0))) {
if (path.segmentCount() == 1) {
// warning because default might vary <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
warning(model, null, path.toString(), cpe,
"Eclipse: The .classpath contains a default JRE container: %s. This makes it undefined to what version you compile and this might differ between Continuous Integration and Eclipse", path).file(
new File(model.getBase(), ".classpath").getAbsolutePath());
} else {
String segment = path.segment(1);
if ("org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType".equals(segment) && path.segmentCount() == 3) {
// check javac version <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
String javac = model.getProperty("javac.source", "1.5");
if (!path.segment(2).endsWith(javac)) {
warning(model, null, path.toString(), cpe, "Eclipse: The .JRE container is set to %s but bnd is compiling against %s", path.segment(2), javac).file(
new File(model.getBase(), ".classpath").getAbsolutePath());
}
} else {
// warning because local/machine specific <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.launching.macosx.MacOSXType/Java SE 7 [1.7.0_71]"/>
warning(model, null, path.toString(), cpe,
"Eclipse: The .classpath contains an non-portable JRE container: %s. This makes it undefined to what version you compile and this might differ between Continuous Integration and Eclipse", path).file(
new File(model.getBase(), ".classpath").getAbsolutePath());
}
}
} else {
warning(model, null, path.toString(), cpe, "Eclipse: The .classpath contains an unknown container: %s", path).file(new File(model.getBase(), ".classpath").getAbsolutePath());
}
}
break;
case IClasspathEntry.CPE_SOURCE :
File file = toFile(cpe.getPath());
if (file == null) {
model.warning("Eclipse: Found virtual file for %s", cpe).details(cpe);
} else {
File output = toFile(cpe.getOutputLocation());
if (output == null)
output = toFile(javaProject.getOutputLocation());
if (file.equals(test)) {
//
// We're talking about the test source directory
// This should be linked to bin_test
//
found.remove(SetupTypes.test);
if (bin_test.equals(output)) {
found.remove(SetupTypes.bin_test);
} else
warning(model, DEFAULT_PROP_TESTBIN_DIR, bin_test, cpe, "Eclipse: Source test folder %s has output set to %s, which does not match bnd's bin_test folder %s", file, output, bin_test);
} else {
//
// We must have a source directory. They must be linked to the bin
// folder and on the bnd source path. Since the source path has
// potentially multiple entries, we remove this one so we can check
// later if we had all of them
//
if (sourcePath.remove(file)) {
if (bin.equals(output)) {
found.remove(SetupTypes.bin);
} else
warning(model, DEFAULT_PROP_BIN_DIR, bin, cpe, "Eclipse: Source folder %s has output set to %s, \n" + "which does not match bnd's bin folder %s", file, output, bin_test);
} else {
warning(model, DEFAULT_PROP_SRC_DIR, null, cpe, "Eclipse: Found source folder %s that is not on the source path %s", file, model.getSourcePath());
}
}
}
break;
default :
break;
}
}
//
// If we had not see all source entries, then we should
// have something in sourcePath
//
for (File f : sourcePath) {
warning(model, DEFAULT_PROP_SRC_DIR, f, null, "Eclipse: Source directory '%s' defined in bnd and not on the Eclipse build path", f);
}
//
// Check if we had all the different things we needed to check
//
for (SetupTypes t : found) {
switch (t) {
case bin :
warning(model, DEFAULT_PROP_BIN_DIR, null, null, "Eclipse: No entry on the build path uses the bnd bin directory %s", bin);
break;
case bin_test :
warning(model, DEFAULT_PROP_TESTBIN_DIR, null, null, "Eclipse: No entry on the build path uses the bnd bin_test directory %s", bin_test);
break;
case bndcontainer :
warning(model, null, null, null, "Eclipse: The build path does not refer to a bnd container");
break;
case test :
warning(model, DEFAULT_PROP_TESTSRC_DIR, null, null, "Eclipse: No test folder %s found", test);
break;
default :
break;
}
}
}
|
bndtools.builder/src/org/bndtools/builder/validate/ProjectPathsValidator.java
|
satd-removal_data_87
|
TODO: init all default-resources
private void fillDefaults()
throws CmsException {
// TODO: init all default-resources
// set the mimetypes
addSystemProperty(C_SYSTEMPROPERTY_MIMETYPES,initMimetypes());
CmsGroup guests = createGroup(C_GROUP_GUEST, "the guest-group", C_FLAG_ENABLED, null);
CmsGroup administrators = createGroup(C_GROUP_ADMIN, "the admin-group", C_FLAG_ENABLED|C_FLAG_GROUP_PROJECTMANAGER, null);
CmsGroup projectleader = createGroup(C_GROUP_PROJECTLEADER, "the projectmanager-group",C_FLAG_ENABLED|C_FLAG_GROUP_PROJECTMANAGER|C_FLAG_GROUP_PROJECTCOWORKER|C_FLAG_GROUP_ROLE,null);
createGroup(C_GROUP_USERS, "the users-group to access the workplace", C_FLAG_ENABLED|C_FLAG_GROUP_ROLE|C_FLAG_GROUP_PROJECTCOWORKER, C_GROUP_GUEST);
CmsUser guest = addUser(C_USER_GUEST, "", "the guest-user", "", "", "", 0, 0, C_FLAG_ENABLED, new Hashtable(), guests, "", "", C_USER_TYPE_SYSTEMUSER);
CmsUser admin = addUser(C_USER_ADMIN, "admin", "the admin-user", "", "", "", 0, 0, C_FLAG_ENABLED, new Hashtable(), administrators, "", "", C_USER_TYPE_SYSTEMUSER);
addUserToGroup(guest.getId(), guests.getId());
addUserToGroup(admin.getId(), administrators.getId());
// TODO: use real task here-when available!
createProject(admin, guests, projectleader, new CmsTask(), C_PROJECT_ONLINE, "the online-project", C_FLAG_ENABLED, C_PROJECT_TYPE_NORMAL);
}
private void fillDefaults()
throws CmsException {
// the resourceType "folder" is needed always - so adding it
Hashtable resourceTypes = new Hashtable(1);
resourceTypes.put(C_TYPE_FOLDER_NAME, new CmsResourceType(C_TYPE_FOLDER, 0,
C_TYPE_FOLDER_NAME, ""));
// sets the last used index of resource types.
resourceTypes.put(C_TYPE_LAST_INDEX, new Integer(C_TYPE_FOLDER));
// add the resource-types to the database
addSystemProperty( C_SYSTEMPROPERTY_RESOURCE_TYPE, resourceTypes );
// set the mimetypes
addSystemProperty(C_SYSTEMPROPERTY_MIMETYPES,initMimetypes());
// set the groups
CmsGroup guests = createGroup(C_GROUP_GUEST, "the guest-group", C_FLAG_ENABLED, null);
CmsGroup administrators = createGroup(C_GROUP_ADMIN, "the admin-group", C_FLAG_ENABLED|C_FLAG_GROUP_PROJECTMANAGER, null);
CmsGroup projectleader = createGroup(C_GROUP_PROJECTLEADER, "the projectmanager-group",C_FLAG_ENABLED|C_FLAG_GROUP_PROJECTMANAGER|C_FLAG_GROUP_PROJECTCOWORKER|C_FLAG_GROUP_ROLE,null);
createGroup(C_GROUP_USERS, "the users-group to access the workplace", C_FLAG_ENABLED|C_FLAG_GROUP_ROLE|C_FLAG_GROUP_PROJECTCOWORKER, C_GROUP_GUEST);
// add the users
CmsUser guest = addUser(C_USER_GUEST, "", "the guest-user", "", "", "", 0, 0, C_FLAG_ENABLED, new Hashtable(), guests, "", "", C_USER_TYPE_SYSTEMUSER);
CmsUser admin = addUser(C_USER_ADMIN, "admin", "the admin-user", "", "", "", 0, 0, C_FLAG_ENABLED, new Hashtable(), administrators, "", "", C_USER_TYPE_SYSTEMUSER);
addUserToGroup(guest.getId(), guests.getId());
addUserToGroup(admin.getId(), administrators.getId());
// TODO: use real task here-when available!
createProject(admin, guests, projectleader, new CmsTask(), C_PROJECT_ONLINE, "the online-project", C_FLAG_ENABLED, C_PROJECT_TYPE_NORMAL);
// create the root-folder
// TODO: createFolder(admin, project, C_ROOT, 0);
}
|
src/com/opencms/file/genericSql/CmsDbAccess.java
|
satd-removal_data_88
|
TODO rayo doesn't support this yes.
@Override
public void acceptWithEarlyMedia(Observer... observer) throws SignalException, MediaException {
// TODO rayo doesn't support this yes.
}
@Override
public void acceptWithEarlyMedia(Observer... observer) throws SignalException, MediaException {
addObserver(observer);
acceptWithEarlyMedia();
}
|
moho-remote/src/main/java/com/voxeo/moho/remote/impl/IncomingCallImpl.java
|
satd-removal_data_89
|
FIXME use the datacenter UUID
private void send(final Datacenter datacenter, final DatacenterTasks tasks,
final EventType event)
{
// FIXME use the datacenter UUID
TarantinoRequestProducer producer = new TarantinoRequestProducer(datacenter.getName());
try
{
producer.openChannel();
producer.publish(tasks);
}
catch (Exception ex)
{
tracer.log(SeverityType.CRITICAL, ComponentType.VIRTUAL_MACHINE, event,
APIError.GENERIC_OPERATION_ERROR.getMessage());
tracer.systemError(SeverityType.CRITICAL, ComponentType.VIRTUAL_MACHINE, event,
"Failed to enqueue task in Tarantino. Rabbitmq might be "
+ "down or not configured. The error message was " + ex.getMessage(), ex);
addNotFoundErrors(APIError.GENERIC_OPERATION_ERROR);
flushErrors();
}
finally
{
closeProducerChannel(producer, event);
}
tracer.log(SeverityType.INFO, ComponentType.VIRTUAL_MACHINE, event,
"Task enqueued successfully to Tarantinio");
}
private void send(final Datacenter datacenter, final DatacenterTasks tasks,
final EventType event)
{
TarantinoRequestProducer producer = new TarantinoRequestProducer(datacenter.getUuid());
try
{
producer.openChannel();
producer.publish(tasks);
}
catch (Exception ex)
{
tracer.log(SeverityType.CRITICAL, ComponentType.VIRTUAL_MACHINE, event,
APIError.GENERIC_OPERATION_ERROR.getMessage());
tracer.systemError(SeverityType.CRITICAL, ComponentType.VIRTUAL_MACHINE, event,
"Failed to enqueue task in Tarantino. Rabbitmq might be "
+ "down or not configured. The error message was " + ex.getMessage(), ex);
addNotFoundErrors(APIError.GENERIC_OPERATION_ERROR);
flushErrors();
}
finally
{
closeProducerChannel(producer, event);
}
tracer.log(SeverityType.INFO, ComponentType.VIRTUAL_MACHINE, event,
"Task enqueued successfully to Tarantinio");
}
|
api/src/main/java/com/abiquo/api/services/stub/TarantinoService.java
|
satd-removal_data_90
|
TODO: fixme -- how do we use this logger?
protected <T> void printOnTraversalDone(final String type, T sum) {
printProgress(true, type, null);
System.out.println("Traversal reduce result is " + sum); // TODO: fixme -- how do we use this logger?
final long curTime = System.currentTimeMillis();
final double elapsed = (curTime - startTime) / 1000.0;
logger.info(String.format("Total runtime %.2f secs, %.2f min, %.2f hours%n", elapsed, elapsed / 60, elapsed / 3600));
logger.info(String.format("Traversal skipped %d reads out of %d total (%.2f%%)", nSkippedReads, nReads, (nSkippedReads * 100.0) / nReads));
logger.info(String.format(" -> %d unmapped reads", nUnmappedReads));
logger.info(String.format(" -> %d non-primary reads", nNotPrimary));
logger.info(String.format(" -> %d reads with bad alignments", nBadAlignments));
logger.info(String.format(" -> %d reads with indels", nSkippedIndels));
}
protected <T> void printOnTraversalDone(final String type, T sum) {
printProgress(true, type, null);
logger.info("Traversal reduce result is " + sum);
final long curTime = System.currentTimeMillis();
final double elapsed = (curTime - startTime) / 1000.0;
logger.info(String.format("Total runtime %.2f secs, %.2f min, %.2f hours%n", elapsed, elapsed / 60, elapsed / 3600));
logger.info(String.format("Traversal skipped %d reads out of %d total (%.2f%%)", nSkippedReads, nReads, (nSkippedReads * 100.0) / nReads));
logger.info(String.format(" -> %d unmapped reads", nUnmappedReads));
logger.info(String.format(" -> %d non-primary reads", nNotPrimary));
logger.info(String.format(" -> %d reads with bad alignments", nBadAlignments));
logger.info(String.format(" -> %d reads with indels", nSkippedIndels));
}
|
java/src/org/broadinstitute/sting/gatk/TraversalEngine.java
|
satd-removal_data_91
|
TODO: need some way to not dispose chunks being edited (or do so safely)
@Override
public void update() {
for (CacheRegion cacheRegion : regions) {
cacheRegion.update();
if (cacheRegion.isDirty()) {
cacheRegion.setUpToDate();
final Region3i reviewRegion = cacheRegion.getRegion().expand(new Vector3i(1, 0, 1));
CoreRegistry.get(GameEngine.class).submitTask("Review chunk region", new Runnable() {
@Override
public void run() {
for (Vector3i chunkPos : reviewRegion) {
Chunk chunk = getChunk(chunkPos);
if (chunk == null) {
PerformanceMonitor.startActivity("Check chunk in cache");
if (farStore.contains(chunkPos) && !fetchPhase.processing(chunkPos)) {
fetchPhase.queue(chunkPos);
} else if (!generatePhase.processing(chunkPos)) {
generatePhase.queue(chunkPos);
}
PerformanceMonitor.endActivity();
} else {
checkState(chunk);
}
}
}
});
}
}
if (fetchPhase.isResultAvailable()) {
Vector3i chunkPos = fetchPhase.poll();
for (Vector3i pos : Region3i.createFromCenterExtents(chunkPos, new Vector3i(1, 0, 1))) {
checkState(pos);
}
}
if (generatePhase.isResultAvailable()) {
Vector3i chunkPos = generatePhase.poll();
logger.log(Level.FINE, "Received generated chunk " + chunkPos);
for (Vector3i pos : Region3i.createFromCenterExtents(chunkPos, new Vector3i(1, 0, 1))) {
checkReadyForSecondPass(pos);
}
}
if (secondPassPhase.isResultAvailable()) {
Vector3i chunkPos = secondPassPhase.poll();
logger.log(Level.FINE, "Received second passed chunk " + chunkPos);
for (Vector3i pos : Region3i.createFromCenterExtents(chunkPos, new Vector3i(1, 0, 1))) {
checkReadyToDoInternalLighting(pos);
}
}
if (internalLightingPhase.isResultAvailable()) {
Vector3i chunkPos = internalLightingPhase.poll();
logger.log(Level.FINE, "Received internally lit chunk " + chunkPos);
for (Vector3i pos : Region3i.createFromCenterExtents(chunkPos, new Vector3i(1, 0, 1))) {
checkReadyToPropagateLighting(pos);
}
}
if (propagateLightPhase.isResultAvailable()) {
Vector3i chunkPos = propagateLightPhase.poll();
logger.log(Level.FINE, "Received second passed chunk " + chunkPos);
for (Vector3i pos : Region3i.createFromCenterExtents(chunkPos, new Vector3i(1, 0, 1))) {
checkComplete(pos);
}
}
PerformanceMonitor.startActivity("Review cache size");
if (nearCache.size() > CACHE_SIZE) {
logger.log(Level.INFO, "Compacting cache");
Iterator<Vector3i> iterator = nearCache.keySet().iterator();
while (iterator.hasNext()) {
Vector3i pos = iterator.next();
boolean keep = false;
for (CacheRegion region : regions) {
if (region.getRegion().expand(new Vector3i(4, 0, 4)).encompasses(pos)) {
keep = true;
break;
}
}
if (!keep) {
for (ChunkPhase phase : phases) {
if (phase.processing(pos)) {
keep = true;
break;
}
}
}
if (!keep) {
// TODO: need some way to not dispose chunks being edited (or do so safely)
Chunk chunk = nearCache.get(pos);
farStore.put(chunk);
iterator.remove();
chunk.dispose();
}
}
}
PerformanceMonitor.endActivity();
}
@Override
public void update() {
for (CacheRegion cacheRegion : regions) {
cacheRegion.update();
if (cacheRegion.isDirty()) {
cacheRegion.setUpToDate();
reviewChunkQueue.offer(new ChunkRequest(ChunkRequest.RequestType.PRODUCE, cacheRegion.getRegion().expand(new Vector3i(2, 0, 2))));
}
}
PerformanceMonitor.startActivity("Review cache size");
if (nearCache.size() > CACHE_SIZE) {
logger.log(Level.INFO, "Compacting cache");
Iterator<Vector3i> iterator = nearCache.keySet().iterator();
while (iterator.hasNext()) {
Vector3i pos = iterator.next();
boolean keep = false;
for (CacheRegion region : regions) {
if (region.getRegion().expand(new Vector3i(4, 0, 4)).encompasses(pos)) {
keep = true;
break;
}
}
if (!keep) {
// TODO: need some way to not dispose chunks being edited or processed (or do so safely)
Chunk chunk = nearCache.get(pos);
if (chunk.isLocked()) {
continue;
}
chunk.lock();
try {
farStore.put(chunk);
iterator.remove();
chunk.dispose();
} finally {
chunk.unlock();
}
}
}
}
PerformanceMonitor.endActivity();
}
|
src/main/java/org/terasology/logic/world/LocalChunkProvider.java
|
satd-removal_data_92
|
TODO: Cache summaries from old categories somehow.
private void rebuildUI() {
if (!isAdded()) {
Log.w(TAG, "Cannot build the DashboardSummary UI yet as the Fragment is not added");
return;
}
long start = System.currentTimeMillis();
// TODO: Cache summaries from old categories somehow.
List<DashboardCategory> categories =
((SettingsActivity) getActivity()).getDashboardCategories();
mAdapter.setCategories(categories);
// recheck to see if any suggestions have been changed.
mAdapter.setSuggestions(mSuggestionParser);
long delta = System.currentTimeMillis() - start;
Log.d(TAG, "rebuildUI took: " + delta + " ms");
}
private void rebuildUI() {
if (!isAdded()) {
Log.w(TAG, "Cannot build the DashboardSummary UI yet as the Fragment is not added");
return;
}
List<DashboardCategory> categories =
((SettingsActivity) getActivity()).getDashboardCategories();
mAdapter.setCategories(categories);
// recheck to see if any suggestions have been changed.
new SuggestionLoader().execute();
}
|
src/com/android/settings/dashboard/DashboardSummary.java
|
satd-removal_data_93
|
TODO exclude Class properties from consideration
@SuppressWarnings("rawtypes")
public void write(Object obj, DBObject dbo) {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(obj);
// This will leverage the conversion service.
initBeanWrapper(bw);
PropertyDescriptor[] propertyDescriptors = BeanUtils
.getPropertyDescriptors(obj.getClass());
for (PropertyDescriptor pd : propertyDescriptors) {
// if (isSimpleType(pd.getPropertyType())) {
Object value = bw.getPropertyValue(pd.getName());
String keyToUse = ("id".equals(pd.getName()) ? "_id" : pd.getName());
if (isValidProperty(pd)) {
// TODO validate Enums...
if (value != null && Enum.class.isAssignableFrom(pd.getPropertyType())) {
writeValue(dbo, keyToUse, ((Enum)value).name());
}
else if (value != null && "_id".equals(keyToUse) && String.class.isAssignableFrom(pd.getPropertyType())) {
try {
ObjectId _id = new ObjectId((String)value);
writeValue(dbo, keyToUse, _id);
}
catch (IllegalArgumentException iae) {
logger.debug("Unable to convert the String " + value
+ " to an ObjectId");
writeValue(dbo, keyToUse, value);
}
}
else {
writeValue(dbo, keyToUse, value);
}
// dbo.put(keyToUse, value);
} else {
//TODO exclude Class properties from consideration
logger.warn("Unable to map property " + pd.getName()
+ ". Skipping.");
}
// }
}
}
@SuppressWarnings("rawtypes")
public void write(Object obj, DBObject dbo) {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(obj);
// This will leverage the conversion service.
initBeanWrapper(bw);
PropertyDescriptor[] propertyDescriptors = BeanUtils
.getPropertyDescriptors(obj.getClass());
for (PropertyDescriptor pd : propertyDescriptors) {
// if (isSimpleType(pd.getPropertyType())) {
Object value = bw.getPropertyValue(pd.getName());
String keyToUse = ("id".equals(pd.getName()) ? "_id" : pd.getName());
if (isValidProperty(pd)) {
// TODO validate Enums...
if (value != null && Enum.class.isAssignableFrom(pd.getPropertyType())) {
writeValue(dbo, keyToUse, ((Enum)value).name());
}
else if (value != null && "_id".equals(keyToUse) && String.class.isAssignableFrom(pd.getPropertyType())) {
try {
ObjectId _id = new ObjectId((String)value);
writeValue(dbo, keyToUse, _id);
}
catch (IllegalArgumentException iae) {
logger.debug("Unable to convert the String " + value
+ " to an ObjectId");
writeValue(dbo, keyToUse, value);
}
}
else {
writeValue(dbo, keyToUse, value);
}
// dbo.put(keyToUse, value);
} else {
if (!"class".equals(pd.getName())) {
logger.warn("Unable to map property " + pd.getName()
+ ". Skipping.");
}
}
// }
}
}
|
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/SimpleMongoConverter.java
|
satd-removal_data_94
|
TODO: context mojo more appropriate?
public void execute()
throws MojoExecutionException
{
getLog().warn( "This goal is deprecated. Please use mvn archetype:generate instead" );
// TODO: prompt for missing values
// TODO: configurable license
// ----------------------------------------------------------------------
// archetypeGroupId
// archetypeArtifactId
// archetypeVersion
//
// localRepository
// remoteRepository
// parameters
// ----------------------------------------------------------------------
if ( project.getFile() != null && groupId == null )
{
groupId = project.getGroupId();
}
if ( packageName == null )
{
getLog().info( "Defaulting package to group ID: " + groupId );
packageName = groupId;
}
// TODO: context mojo more appropriate?
Map parameters = new HashMap();
parameters.put( "basedir", basedir );
parameters.put( "package", packageName );
parameters.put( "packageName", packageName );
parameters.put( "groupId", groupId );
parameters.put( "artifactId", artifactId );
parameters.put( "version", version );
List archetypeRemoteRepositories = new ArrayList( pomRemoteRepositories );
if ( remoteRepositories != null )
{
getLog().info( "We are using command line specified remote repositories: " + remoteRepositories );
archetypeRemoteRepositories = new ArrayList();
String[] s = StringUtils.split( remoteRepositories, "," );
for ( int i = 0; i < s.length; i++ )
{
archetypeRemoteRepositories.add( createRepository( s[i], "id" + i ) );
}
}
try
{
archetype.createArchetype( archetypeGroupId, archetypeArtifactId, archetypeVersion,
createRepository( "http://repo1.maven.org/maven2", "central" ), localRepository,
archetypeRemoteRepositories, parameters );
}
catch ( UnknownArchetype e )
{
throw new MojoExecutionException( "Error creating from archetype", e );
}
catch ( ArchetypeNotFoundException e )
{
throw new MojoExecutionException( "Error creating from archetype", e );
}
catch ( ArchetypeDescriptorException e )
{
throw new MojoExecutionException( "Error creating from archetype", e );
}
catch ( ArchetypeTemplateProcessingException e )
{
throw new MojoExecutionException( "Error creating from archetype", e );
}
}
public void execute()
throws MojoExecutionException
{
getLog().warn( "This goal is deprecated. Please use mvn archetype:generate instead" );
// TODO: prompt for missing values
// TODO: configurable license
// ----------------------------------------------------------------------
// archetypeGroupId
// archetypeArtifactId
// archetypeVersion
//
// localRepository
// remoteRepository
// parameters
// ----------------------------------------------------------------------
if ( project.getFile() != null && groupId == null )
{
groupId = project.getGroupId();
}
if ( packageName == null )
{
getLog().info( "Defaulting package to group ID: " + groupId );
packageName = groupId;
}
List archetypeRemoteRepositories = new ArrayList( pomRemoteRepositories );
if ( remoteRepositories != null )
{
getLog().info( "We are using command line specified remote repositories: " + remoteRepositories );
archetypeRemoteRepositories = new ArrayList();
String[] s = StringUtils.split( remoteRepositories, "," );
for ( int i = 0; i < s.length; i++ )
{
archetypeRemoteRepositories.add( createRepository( s[i], "id" + i ) );
}
}
try
{
ArchetypeGenerationRequest request = new ArchetypeGenerationRequest()
.setPackage( packageName )
.setGroupId( groupId )
.setArtifactId( artifactId )
.setVersion( version )
.setArchetypeGroupId( archetypeGroupId )
.setArchetypeArtifactId( archetypeArtifactId )
.setArchetypeVersion( archetypeVersion )
.setLocalRepository( localRepository )
.setRemoteArtifactRepositories( archetypeRemoteRepositories );
archetype.createArchetype( request, createRepository( "http://repo1.maven.org/maven2", "central" ), basedir );
}
catch ( UnknownArchetype e )
{
throw new MojoExecutionException( "Error creating from archetype", e );
}
catch ( ArchetypeNotFoundException e )
{
throw new MojoExecutionException( "Error creating from archetype", e );
}
catch ( ArchetypeDescriptorException e )
{
throw new MojoExecutionException( "Error creating from archetype", e );
}
catch ( ArchetypeTemplateProcessingException e )
{
throw new MojoExecutionException( "Error creating from archetype", e );
}
}
|
archetype-plugin/src/main/java/org/apache/maven/archetype/mojos/MavenArchetypeMojo.java
|
satd-removal_data_95
|
TODO: oldParentState is overlayed state from workspace. do not use!
public void checkIsSelfContained()
throws ItemStateException {
Set affectedStates = new HashSet();
affectedStates.addAll(modifiedStates);
affectedStates.addAll(deletedStates);
affectedStates.addAll(addedStates);
Iterator it = new IteratorChain(modifiedStates(), deletedStates());
while (it.hasNext()) {
ItemState transientState = (ItemState) it.next();
if (transientState.isNode()) {
NodeState nodeState = (NodeState) transientState;
Set dependentStates = new HashSet();
if (nodeState.hasOverlayedState()) {
// TODO: oldParentState is overlayed state from workspace. do not use!
NodeState oldParentState = nodeState.getOverlayedState().getParent();
NodeState newParentState = nodeState.getParent();
if (oldParentState != null) {
if (newParentState == null) {
// node has been removed, add old parent
// to dependencies
dependentStates.add(oldParentState);
} else {
if (!oldParentState.equals(newParentState)) {
// node has been moved, add old and new parent
// to dependencies
dependentStates.add(oldParentState);
dependentStates.add(newParentState);
}
}
}
}
// removed child node entries
Iterator cneIt = nodeState.getRemovedChildNodeEntries().iterator();
while (cneIt.hasNext()) {
ChildNodeEntry cne = (ChildNodeEntry) cneIt.next();
dependentStates.add(cne.getNodeState());
}
// added child node entries
cneIt = nodeState.getAddedChildNodeEntries().iterator();
while (cneIt.hasNext()) {
ChildNodeEntry cne = (ChildNodeEntry) cneIt.next();
dependentStates.add(cne.getNodeState());
}
// now walk through dependencies and check whether they
// are within the scope of this save operation
Iterator depIt = dependentStates.iterator();
while (depIt.hasNext()) {
NodeState dependantState = (NodeState) depIt.next();
if (!affectedStates.contains(dependantState)) {
// need to save the parent as well
String msg = dependantState.getNodeId().toString() + " needs to be saved as well.";
throw new ItemStateException(msg);
}
}
}
}
}
public void checkIsSelfContained()
throws ItemStateException {
Set affectedStates = new HashSet();
affectedStates.addAll(modifiedStates);
affectedStates.addAll(deletedStates);
affectedStates.addAll(addedStates);
// check if the affected states listed by the operations are all
// listed in the modified,deleted or added states collected by this
// changelog.
Iterator it = getOperations();
while (it.hasNext()) {
Operation op = (Operation) it.next();
Collection opStates = op.getAffectedItemStates();
if (!affectedStates.containsAll(opStates)) {
// need to save the parent as well
String msg = "ChangeLog is not self contained.";
throw new ItemStateException(msg);
}
}
}
|
contrib/spi/jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/state/ChangeLog.java
|
satd-removal_data_96
|
TODO: packaging2extension mapping, now we default to JAR
public void storeArtifact( GAVRequest gavRequest, InputStream is )
throws UnsupportedStorageOperationException,
NoSuchResourceStoreException,
RepositoryNotAvailableException,
StorageException,
AccessDeniedException
{
checkRequest( gavRequest );
// TODO: packaging2extension mapping, now we default to JAR
Gav gav = new Gav( gavRequest.getGroupId(), gavRequest.getArtifactId(), gavRequest.getVersion(), gavRequest
.getClassifier(), "jar", null, null, null, RepositoryPolicy.SNAPSHOT.equals( repository
.getRepositoryPolicy() ), false, null );
DefaultStorageFileItem file = new DefaultStorageFileItem( repository, repository.getGavCalculator().gavToPath(
gav ), true, true, new PreparedContentLocator( is ) );
storeItemWithChecksums( file );
}
public void storeArtifact( GAVRequest gavRequest, InputStream is )
throws UnsupportedStorageOperationException,
NoSuchResourceStoreException,
RepositoryNotAvailableException,
StorageException,
AccessDeniedException
{
checkRequest( gavRequest );
if ( gavRequest.getPackaging() == null )
{
throw new IllegalArgumentException( "Cannot generate POM without valid 'packaging'!" );
}
Gav gav = new Gav( gavRequest.getGroupId(), gavRequest.getArtifactId(), gavRequest.getVersion(), gavRequest
.getClassifier(), repository.getArtifactPackagingMapper().getExtensionForPackaging(
gavRequest.getPackaging() ), null, null, null, RepositoryPolicy.SNAPSHOT.equals( repository
.getRepositoryPolicy() ), false, null );
DefaultStorageFileItem file = new DefaultStorageFileItem( repository, repository.getGavCalculator().gavToPath(
gav ), true, true, new PreparedContentLocator( is ) );
storeItemWithChecksums( file );
}
|
nexus/nexus-proxy/src/main/java/org/sonatype/nexus/proxy/maven/ArtifactStoreHelper.java
|
satd-removal_data_97
|
FIXME: we really need to behave better than this
public void destroy() {
if (lock.isHeld()) {
throw new GLException("Can not destroy context while it is current");
}
if (tracker != null) {
// Don't need to do anything for contexts that haven't been
// created yet
if (isCreated()) {
// If we are tracking creation and destruction of server-side
// OpenGL objects, we must decrement the reference count of the
// GLObjectTracker upon context destruction.
try {
int res = makeCurrent();
if (res != CONTEXT_CURRENT) {
// FIXME: we really need to behave better than this
throw new GLException("Unable to make context current to destroy tracked server-side OpenGL objects");
}
try {
tracker.unref(getGL());
} finally {
release();
}
} catch (GLException e) {
// FIXME: should probably do something more intelligent here
if (DEBUG) {
e.printStackTrace();
}
}
}
}
// Must hold the lock around the destroy operation to make sure we
// don't destroy the context out from under another thread rendering to it
lock.lock();
try {
destroyImpl();
} finally {
lock.unlock();
}
}
public void destroy() {
if (lock.isHeld()) {
throw new GLException("Can not destroy context while it is current");
}
if (tracker != null) {
// Don't need to do anything for contexts that haven't been
// created yet
if (isCreated()) {
// If we are tracking creation and destruction of server-side
// OpenGL objects, we must decrement the reference count of the
// GLObjectTracker upon context destruction.
//
// Note that we can only eagerly delete these server-side
// objects if there is another context currrent right now
// which shares textures and display lists with this one.
tracker.unref(deletedObjectTracker);
}
}
// Must hold the lock around the destroy operation to make sure we
// don't destroy the context out from under another thread rendering to it
lock.lock();
try {
destroyImpl();
} finally {
lock.unlock();
}
}
|
src/classes/com/sun/opengl/impl/GLContextImpl.java
|
satd-removal_data_98
|
check for xpath validation - old style with direct attribute TODO: remove with next major version
private void parseValidationElements(Element messageElement, XmlMessageValidationContext context) {
//check for validate elements, these elements can either have script, xpath or namespace validation information
//script validation is handled separately for now we only handle xpath and namepsace validation
Map<String, String> validateNamespaces = new HashMap<String, String>();
Map<String, String> validateXpathExpressions = new HashMap<String, String>();
List<?> validateElements = DomUtils.getChildElementsByTagName(messageElement, "validate");
if (validateElements.size() > 0) {
for (Iterator<?> iter = validateElements.iterator(); iter.hasNext();) {
Element validateElement = (Element) iter.next();
//check for xpath validation - old style with direct attribute TODO: remove with next major version
String pathExpression = validateElement.getAttribute("path");
if (StringUtils.hasText(pathExpression)) {
//construct pathExpression with explicit result-type, like boolean:/TestMessage/Value
if (validateElement.hasAttribute("result-type")) {
pathExpression = validateElement.getAttribute("result-type") + ":" + pathExpression;
}
validateXpathExpressions.put(pathExpression, validateElement.getAttribute("value"));
}
//check for xpath validation elements - new style preferred
List<?> xpathElements = DomUtils.getChildElementsByTagName(validateElement, "xpath");
if (xpathElements.size() > 0) {
for (Iterator<?> xpathIterator = xpathElements.iterator(); xpathIterator.hasNext();) {
Element xpathElement = (Element) xpathIterator.next();
String expression = xpathElement.getAttribute("expression");
if (StringUtils.hasText(expression)) {
//construct expression with explicit result-type, like boolean:/TestMessage/Value
if (xpathElement.hasAttribute("result-type")) {
expression = xpathElement.getAttribute("result-type") + ":" + expression;
}
validateXpathExpressions.put(expression, xpathElement.getAttribute("value"));
}
}
}
//check for namespace validation elements
List<?> validateNamespaceElements = DomUtils.getChildElementsByTagName(validateElement, "namespace");
if (validateNamespaceElements.size() > 0) {
for (Iterator<?> namespaceIterator = validateNamespaceElements.iterator(); namespaceIterator.hasNext();) {
Element namespaceElement = (Element) namespaceIterator.next();
validateNamespaces.put(namespaceElement.getAttribute("prefix"), namespaceElement.getAttribute("value"));
}
}
}
context.setPathValidationExpressions(validateXpathExpressions);
context.setControlNamespaces(validateNamespaces);
}
}
private void parseValidationElements(Element messageElement, XmlMessageValidationContext context) {
//check for validate elements, these elements can either have script, xpath or namespace validation information
//script validation is handled separately for now we only handle xpath and namepsace validation
Map<String, String> validateNamespaces = new HashMap<String, String>();
Map<String, String> validateXpathExpressions = new HashMap<String, String>();
List<?> validateElements = DomUtils.getChildElementsByTagName(messageElement, "validate");
if (validateElements.size() > 0) {
for (Iterator<?> iter = validateElements.iterator(); iter.hasNext();) {
Element validateElement = (Element) iter.next();
extractXPathValidateExpressions(validateElement, validateXpathExpressions);
//check for namespace validation elements
List<?> validateNamespaceElements = DomUtils.getChildElementsByTagName(validateElement, "namespace");
if (validateNamespaceElements.size() > 0) {
for (Iterator<?> namespaceIterator = validateNamespaceElements.iterator(); namespaceIterator.hasNext();) {
Element namespaceElement = (Element) namespaceIterator.next();
validateNamespaces.put(namespaceElement.getAttribute("prefix"), namespaceElement.getAttribute("value"));
}
}
}
context.setPathValidationExpressions(validateXpathExpressions);
context.setControlNamespaces(validateNamespaces);
}
}
|
modules/citrus-core/src/main/java/com/consol/citrus/config/xml/ReceiveMessageActionParser.java
|
satd-removal_data_99
|
TODO handle error.
public void postMessage()
{
StreamScope scope = postToPanel.getPostScope();
if (scope != null)
{
if (scope.getScopeType().equals(ScopeType.PERSON))
{
recipientType = EntityType.PERSON;
}
else
{
recipientType = EntityType.GROUP;
}
actionKeys.put(EntityType.GROUP, "postGroupActivityServiceActionTaskHandler");
actionKeys.put(EntityType.PERSON, "postPersonActivityServiceActionTaskHandler");
ActivityDTOPopulatorStrategy objectStrat = new NotePopulator();
if (attachment != null)
{
objectStrat = attachment.getPopulator();
}
PostActivityRequest postRequest = new PostActivityRequest(
activityPopulator
.getActivityDTO(message, recipientType, scope
.getUniqueKey(), new PostPopulator(), objectStrat));
processor.makeRequest(new ActionRequestImpl<Integer>(actionKeys
.get(recipientType), postRequest),
new AsyncCallback<ActivityDTO>()
{
/* implement the async call back methods */
public void onFailure(final Throwable caught)
{
// TODO handle error.
}
public void onSuccess(final ActivityDTO result)
{
MessageStreamAppendEvent msgEvent = new MessageStreamAppendEvent(
result);
eventBus.notifyObservers(msgEvent);
}
});
}
else
{
ErrorPostingMessageToNullScopeEvent error = new ErrorPostingMessageToNullScopeEvent();
error
.setErrorMsg("The stream name you entered could not be found");
eventBus.notifyObservers(error);
}
}
public void postMessage()
{
StreamScope scope = postToPanel.getPostScope();
if (scope != null)
{
if (scope.getScopeType().equals(ScopeType.PERSON))
{
recipientType = EntityType.PERSON;
}
else
{
recipientType = EntityType.GROUP;
}
actionKeys.put(EntityType.GROUP, "postGroupActivityServiceActionTaskHandler");
actionKeys.put(EntityType.PERSON, "postPersonActivityServiceActionTaskHandler");
ActivityDTOPopulatorStrategy objectStrat = new NotePopulator();
if (attachment != null)
{
objectStrat = attachment.getPopulator();
}
PostActivityRequest postRequest = new PostActivityRequest(activityPopulator.getActivityDTO(message,
recipientType, scope.getUniqueKey(), new PostPopulator(), objectStrat));
processor.makeRequest(new ActionRequestImpl<Integer>(actionKeys.get(recipientType), postRequest),
new AsyncCallback<ActivityDTO>()
{
/* implement the async call back methods */
public void onFailure(final Throwable caught)
{
String errorMessage = "Error posting to stream.";
if (caught instanceof AuthorizationException)
{
errorMessage = "Not allowed to post to this stream.";
}
eventBus.notifyObservers(new ShowNotificationEvent(new Notification(errorMessage)));
}
public void onSuccess(final ActivityDTO result)
{
MessageStreamAppendEvent msgEvent = new MessageStreamAppendEvent(result);
eventBus.notifyObservers(msgEvent);
}
});
}
else
{
ErrorPostingMessageToNullScopeEvent error = new ErrorPostingMessageToNullScopeEvent();
error.setErrorMsg("The stream name you entered could not be found");
eventBus.notifyObservers(error);
}
}
|
web/src/main/java/org/eurekastreams/web/client/ui/common/stream/PostToStreamModel.java
|
satd-removal_data_100
|
TODO: Improve this
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event)
{
Player player = event.getPlayer();
Mage apiMage = getMage(player);
if (!(apiMage instanceof com.elmakers.mine.bukkit.magic.Mage)) return;
com.elmakers.mine.bukkit.magic.Mage mage = (com.elmakers.mine.bukkit.magic.Mage)apiMage;
final Wand activeWand = mage.getActiveWand();
ItemStack droppedItem = event.getItemDrop().getItemStack();
// TODO: Improve this
if (Wand.isWand(droppedItem) && activeWand != null) {
if (activeWand.isUndroppable()) {
event.setCancelled(true);
return;
}
}
if (activeWand != null) {
ItemStack inHand = event.getPlayer().getInventory().getItemInHand();
// Kind of a hack- check if we just dropped a wand, and now have an empty hand
if (Wand.isWand(droppedItem) && (inHand == null || inHand.getType() == Material.AIR)) {
activeWand.deactivate();
// Clear after inventory restore (potentially with deactivate), since that will put the wand back
if (Wand.hasActiveWand(player)) {
player.setItemInHand(new ItemStack(Material.AIR, 1));
}
} else if (activeWand.isInventoryOpen()) {
if (!spellDroppingEnabled) {
// This is needed a a work-around for glitches that happen when this
// event is cancelled!
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
public void run() {
activeWand.closeInventory();
}
}, 1);
event.setCancelled(true);
return;
}
// The item is already removed from the wand's inventory, but that should be ok
removeItemFromWand(activeWand, droppedItem);
// Cancelling the event causes some really strange behavior, including the item
// being put back in the inventory.
// So instead of cancelling, we'll try and update the returned item in place.
}
}
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event)
{
Player player = event.getPlayer();
Mage apiMage = getMage(player);
if (!(apiMage instanceof com.elmakers.mine.bukkit.magic.Mage)) return;
com.elmakers.mine.bukkit.magic.Mage mage = (com.elmakers.mine.bukkit.magic.Mage)apiMage;
final Wand activeWand = mage.getActiveWand();
ItemStack droppedItem = event.getItemDrop().getItemStack();
boolean cancelEvent = false;
if (Wand.isWand(droppedItem) && activeWand != null && activeWand.isUndroppable()) {
cancelEvent = true;
} else if (activeWand != null) {
ItemStack inHand = event.getPlayer().getInventory().getItemInHand();
// Kind of a hack- check if we just dropped a wand, and now have an empty hand
if (Wand.isWand(droppedItem) && (inHand == null || inHand.getType() == Material.AIR)) {
activeWand.deactivate();
// Clear after inventory restore (potentially with deactivate), since that will put the wand back
if (Wand.hasActiveWand(player)) {
player.setItemInHand(new ItemStack(Material.AIR, 1));
}
} else if (activeWand.isInventoryOpen()) {
if (!spellDroppingEnabled) {
cancelEvent = true;
} else {
// The item is already removed from the wand's inventory, but that should be ok
removeItemFromWand(activeWand, droppedItem);
}
}
}
// Cancelling the event causes some really strange behavior, including the item
// being put back in the inventory. (This bug's been in CB since 1.6!!!)
// Thanks to this thread for a hacky, but effective solution:
// https://forums.bukkit.org/threads/cancelling-item-dropping.111676/page-2
if (cancelEvent) {
PlayerInventory playerInventory = player.getInventory();
ItemStack cloneItem = InventoryUtils.getCopy(droppedItem);
Item drop = event.getItemDrop();
drop.setItemStack(new ItemStack(Material.AIR, 1));
drop.remove();
// This hopefully only gets called for the held item...
playerInventory.setItem(playerInventory.getHeldItemSlot(), cloneItem);
}
}
|
src/main/java/com/elmakers/mine/bukkit/magic/MagicController.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.