_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q168900
SPFRemoteProfile.getProfileOf
validation
public RemoteProfile getProfileOf(SPFPerson p) { if (p == null) { throw new NullPointerException(); } return new RemoteProfile(p, mInterface); }
java
{ "resource": "" }
q168901
TagsPicker.setChangeListener
validation
public void setChangeListener(OnChangeListener listener) { changeListener = listener; if (changeListener != null) { // add a listener to TagViewer for removed tags events tv.setOnRemovedTagListener(new TagsViewer.OnRemovedListener() { @Override public void onRemovedTag(String tag) { notifyChangeListener(); } }); } }
java
{ "resource": "" }
q168902
ValidatorExtensions.getDocumentBuilderFactory
validation
public static DocumentBuilderFactory getDocumentBuilderFactory(final String schema) { System.setProperty(DOCUMENT_BUILDER_FACTORY_KEY, DOCUMENT_BUILDER_FACTORY_VALUE); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute(SCHEMA_LANGUAGE_KEY, HTTP_WWW_W3_ORG_2001_XML_SCHEMA); factory.setAttribute(SCHEMA_SOURCE_KEY, schema); return factory; }
java
{ "resource": "" }
q168903
ValidatorExtensions.getDOMSource
validation
public static DOMSource getDOMSource(final File xml, final ErrorHandler errorHandler) throws SAXException, ParserConfigurationException, IOException { return new DOMSource(parse(xml, errorHandler)); }
java
{ "resource": "" }
q168904
ValidatorExtensions.getSchema
validation
public static Schema getSchema(final File xsd, final ErrorHandler errorHandler) throws SAXException { // Create a new instance for an XSD-aware SchemaFactory final SchemaFactory schemaFactory = SchemaFactory .newInstance(HTTP_WWW_W3_ORG_2001_XML_SCHEMA); // Set the ErrorHandler implementation. schemaFactory.setErrorHandler(errorHandler); // get the custom xsd schema that describes // the required format for my XML files. return schemaFactory.newSchema(xsd); }
java
{ "resource": "" }
q168905
ValidatorExtensions.parse
validation
public static Document parse(final File xml, final ErrorHandler errorHandler) throws SAXException, ParserConfigurationException, IOException { final DocumentBuilderFactory factory = getDocumentBuilderFactory(xml.getName()); final DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); return builder.parse(xml); }
java
{ "resource": "" }
q168906
ValidatorExtensions.validateSchema
validation
public static void validateSchema(final File xsd, final File xml, final ErrorHandler errorHandler) throws SAXException, ParserConfigurationException, IOException { final Schema schemaXSD = getSchema(xsd, errorHandler); // Create a Validator capable of validating XML files according to my custom schema. final Validator validator = schemaXSD.newValidator(); // parse the XML DOM tree againts the stricter XSD schema validator.validate(getDOMSource(xml, errorHandler)); }
java
{ "resource": "" }
q168907
ValidatorExtensions.validateSchema
validation
public static boolean validateSchema(final String SchemaUrl, final String XmlDocumentUrl) throws SAXException, ParserConfigurationException, IOException { System.setProperty(DOCUMENT_BUILDER_FACTORY_KEY, DOCUMENT_BUILDER_FACTORY_VALUE); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute(SCHEMA_LANGUAGE_KEY, HTTP_WWW_W3_ORG_2001_XML_SCHEMA); factory.setAttribute(SCHEMA_SOURCE_KEY, SchemaUrl); final DocumentBuilder builder = factory.newDocumentBuilder(); final ValidatorHandler handler = new ValidatorHandler(); builder.setErrorHandler(handler); builder.parse(XmlDocumentUrl); if (handler.isValid()) { return false; } return true; }
java
{ "resource": "" }
q168908
SimpleTag.addChild
validation
public boolean addChild(final SimpleTag child) { if (getChildren() == null) { setChildren(ListFactory.newArrayList()); } return getChildren().add(child); }
java
{ "resource": "" }
q168909
SimpleTag.removeAttribute
validation
public String removeAttribute(final String name) { if (getAttributes() != null) { getAttributes().remove(name); } return null; }
java
{ "resource": "" }
q168910
SimpleTag.toVelocityTemplate
validation
public StringBuilder toVelocityTemplate() { final StringBuilder buffer = new StringBuilder(); buffer.append("<"); buffer.append("${").append(getName()).append(".name}\n"); if (getAttributes() != null && !getAttributes().isEmpty()) { buffer.append(" #foreach(" + "$attribute in $").append(getName()) .append(".attributes.keySet()" + ")\n"); buffer.append("$attribute=\"$").append(getName()) .append(".getAttributes().get($attribute)\"\n"); buffer.append(" #end\n"); } buffer.append("#if(${").append(getName()).append(".endTag})>${").append(getName()) .append(".content}\n"); if (getChildren() != null && !getChildren().isEmpty()) { buffer.append("#foreach($").append(getChildren().get(0).getName()).append(" in $") .append(getName()).append(".children)\n"); for (final SimpleTag child : getChildren()) { buffer.append(child.toVelocityTemplate().toString()); } buffer.append("#end\n"); } buffer.append("</${").append(getName()).append(".name}>\n"); buffer.append("#else />\n" + "#end\n"); return buffer; }
java
{ "resource": "" }
q168911
SimpleTag.toXmlString
validation
public String toXmlString() { final StringBuilder buffer = new StringBuilder(); buffer.append("<"); buffer.append(getName()); Optional<String> attr = TagExtensions.attributesToString(getAttributes()); if (attr.isPresent()) { buffer.append(attr.get()); } if (isEndTag()) { buffer.append(">"); buffer.append(getContent()); if (getChildren() != null && !getChildren().isEmpty()) { for (final SimpleTag child : getChildren()) { buffer.append(child.toXmlString()); } } buffer.append("</"); buffer.append(getName()); buffer.append(">"); } else { buffer.append("/>"); } return buffer.toString(); }
java
{ "resource": "" }
q168912
ServiceList.addServiceIfNotPresent
validation
public void addServiceIfNotPresent(WiFiP2pService service) { WfdLog.d(TAG, "addServiceIfNotPresent BEGIN, with size = " + serviceList.size()); if (service == null) { WfdLog.e(TAG, "Service is null, returning..."); return; } boolean add = true; for (WiFiP2pService element : serviceList) { if (element != null && element.getDevice().equals(service.getDevice()) && element.getInstanceName().equals(service.getInstanceName())) { add = false; //already in the list } } if (add) { serviceList.add(service); } WfdLog.d(TAG, "addServiceIfNotPresent END, with size = " + serviceList.size()); }
java
{ "resource": "" }
q168913
ServiceList.getServiceByDevice
validation
public WiFiP2pService getServiceByDevice(WifiP2pDevice device) { if (device == null) { return null; } WfdLog.d(TAG, "groupownerdevice passed to getServiceByDevice: " + device.deviceName + ", " + device.deviceAddress); WfdLog.d(TAG, "servicelist size: " + serviceList.size()); for (WiFiP2pService element : serviceList) { WfdLog.d(TAG, "element in list: " + element.getDevice().deviceName + ", " + element.getDevice().deviceAddress); WfdLog.d(TAG, "element passed : " + device.deviceName + ", " + device.deviceAddress); if (element.getDevice().deviceAddress.equals(device.deviceAddress)) { WfdLog.d(TAG, "getServiceByDevice if satisfied : " + device.deviceAddress + ", " + element.getDevice().deviceAddress); return element; } } WfdLog.d(TAG, "servicelist size: " + serviceList.size()); return null; }
java
{ "resource": "" }
q168914
SPFService.onStartCommand
validation
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) { return START_STICKY; } String action = intent.getAction(); if (ACTION_START_FOREGROUND.equals(action)) { if (!SPF.get().isConnected()) { SPF.get().connect(); } SPF.get().notifyProximityStatus(false); //false because it's starting startInForeground(); Log.d(TAG, "Started in foreground"); } else if (ACTION_STOP_FOREGROUND.equals(action)) { //notify to the middleware that i killed the proximity service SPF.get().notifyProximityStatus(true); //true because it's killing stopForeground(true); mIsStartedForeground = false; Log.d(TAG, "Foreground stopped"); } return START_STICKY; }
java
{ "resource": "" }
q168915
SPFTriggerTable.getAllTriggers
validation
List<SPFTrigger> getAllTriggers(String appIdentifier) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ?"; String[] whereArgs = { appIdentifier }; Cursor c = getReadableDatabase().query(Contract.TABLE_NAME, null, where, whereArgs, null, null, null); List<SPFTrigger> triggers = new ArrayList<SPFTrigger>(); while (c.moveToNext()) { triggers.add(triggerFromCursor(c)); } c.close(); return triggers; }
java
{ "resource": "" }
q168916
SPFTriggerTable.deleteAllTriggerOf
validation
boolean deleteAllTriggerOf(String appPackageName) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ?"; String[] whereArgs = { appPackageName }; int c = getReadableDatabase().delete(Contract.TABLE_NAME, where, whereArgs); return c > 0; }
java
{ "resource": "" }
q168917
SPFTriggerTable.deleteTrigger
validation
boolean deleteTrigger(long id, String appPackageName) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ? AND " + Contract._ID + " = ?"; String[] whereArgs = { appPackageName, Long.toString(id) }; int count = getReadableDatabase().delete(Contract.TABLE_NAME, where, whereArgs); return count > 0; }
java
{ "resource": "" }
q168918
SPFTriggerTable.getTrigger
validation
SPFTrigger getTrigger(long triggerId, String appPackageName) { String where = Contract._ID + " = ? AND " + Contract.COLUMN_APP_IDENTIFIER + " = ?"; String[] whereArgs = { Long.toString(triggerId), appPackageName }; Cursor c = getReadableDatabase().query(Contract.TABLE_NAME, null, where, whereArgs, null, null, null); if (!c.moveToFirst()) { return null; } SPFTrigger t = triggerFromCursor(c); c.close(); return t; }
java
{ "resource": "" }
q168919
SPFSecurityMonitor.validateAccess
validation
public AppAuth validateAccess(String accessToken, Permission permission) throws TokenNotValidException, PermissionDeniedException { AppAuth appAuth; if (accessToken == null) { throw new TokenNotValidException(); } appAuth = mAppRegistry.getAppAuthorization(accessToken); if ((appAuth.getPermissionCode() & permission.getCode()) == 0) { throw new PermissionDeniedException(); } return appAuth; }
java
{ "resource": "" }
q168920
XmlToObjectExtensions.toObjectWithXStream
validation
public static <T> T toObjectWithXStream(final String xmlString, final Map<String, Class<?>> aliases) { return toObjectWithXStream(null, xmlString, aliases); }
java
{ "resource": "" }
q168921
XmlToObjectExtensions.toObjectWithXStream
validation
@SuppressWarnings("unchecked") public static <T> T toObjectWithXStream(XStream xstream, final String xmlString, final Map<String, Class<?>> aliases) { if (xstream == null) { xstream = new XStream(); } if (aliases != null) { for (final Map.Entry<String, Class<?>> alias : aliases.entrySet()) { xstream.alias(alias.getKey(), alias.getValue()); } } return (T)xstream.fromXML(xmlString); }
java
{ "resource": "" }
q168922
XmlToJsonExtensions.toJson
validation
public static String toJson(final String xmlString, final Map<String, Class<?>> aliases) { final Object object = XmlToObjectExtensions.toObjectWithXStream(xmlString); final XStream xstream = new XStream(new JettisonMappedXmlDriver()); if (aliases != null) { for (final Map.Entry<String, Class<?>> alias : aliases.entrySet()) { xstream.alias(alias.getKey(), alias.getValue()); } } final String json = xstream.toXML(object); return json; }
java
{ "resource": "" }
q168923
InvocationStub.invokeMethod
validation
public Object invokeMethod(String methodName, Object[] args, Type retType) throws ServiceInvocationException { checkCurrentThread(methodName); Utils.notNull(methodName); Utils.notNull(args); // Let the target prepare the arguments if needed mInvocationTarget.prepareArguments(args); // Serialize arguments String payload = GsonHelper.gson.toJson(args); InvocationRequest request = new InvocationRequest(mServiceDescriptor.getAppIdentifier(), mServiceDescriptor.getServiceName(), methodName, payload); // Let the target perform the execution InvocationResponse response = mInvocationTarget.executeService(request); // Analyze the response if (!response.isResult()) { throw new ServiceInvocationException(response.getErrorMessage()); } else if (retType.equals(void.class)) { return null; } else { return GsonHelper.gson.fromJson(response.getPayload(), retType); } }
java
{ "resource": "" }
q168924
InvocationStub.checkCurrentThread
validation
private void checkCurrentThread(String methodName) { if (Looper.myLooper() == Looper.getMainLooper()) { Log.w(TAG, String.format(WRONG_THREAD_MSG, mServiceDescriptor.getServiceName(), methodName)); } }
java
{ "resource": "" }
q168925
Utils.logCall
validation
public static void logCall(String tag, String methodName, Object... args) { if (SPFConfig.DEBUG) { Log.d(tag, "method call: " + methodName + "(" + (args != null ? TextUtils.join(",", args) : "") + ")"); } }
java
{ "resource": "" }
q168926
XmlExtensions.loadObject
validation
private static <T> T loadObject(final InputStream is) throws IOException { final String xmlString = ReadFileExtensions.inputStream2String(is); final T object = XmlToObjectExtensions.toObjectWithXStream(xmlString); return object; }
java
{ "resource": "" }
q168927
XmlExtensions.newTag
validation
public static String newTag(final String tagname, final String value, final Map<String, String> attributes) { final StringBuilder xmlTag = new StringBuilder(); xmlTag.append("<").append(tagname); if (attributes != null && !attributes.isEmpty()) { xmlTag.append(" "); int count = 1; for (final Map.Entry<String, String> attributte : attributes.entrySet()) { xmlTag.append(attributte.getKey()); xmlTag.append("="); xmlTag.append("\"").append(attributte.getValue()).append("\""); if (count != attributes.size()) { xmlTag.append(" "); } count++; } } xmlTag.append(">"); xmlTag.append(value); xmlTag.append("</").append(tagname).append(">"); return xmlTag.toString(); }
java
{ "resource": "" }
q168928
SearchResponder.matches
validation
public boolean matches(String queryJSON) { QueryContainer queryContainer; try { queryContainer = QueryContainer.fromJSON(queryJSON); } catch (JSONException e) { return false; } SPFQuery query = queryContainer.getQuery(); String callerApp = queryContainer.getCallerAppId(); String userUID = queryContainer.getUserUID(); return analyzeWith(query, callerApp, userUID); }
java
{ "resource": "" }
q168929
SPFServiceRegistry.dispatchInvocation
validation
public InvocationResponse dispatchInvocation(InvocationRequest request) { String appName = request.getAppName(); String serviceName = request.getServiceName(); String componentName = mServiceTable.getComponentForService(appName, serviceName); if (componentName == null) { return InvocationResponse.error("Application " + appName + " doesn't have a service named " + serviceName); } AppServiceProxy proxy = mCommunicationAgent.getProxy(componentName); if (proxy == null) { return InvocationResponse.error("Cannot bind to service"); } try { return proxy.executeService(request); } catch (Throwable t) { Log.e("ServiceRegistry", "Error dispatching invocation: ", t); return InvocationResponse.error("Internal error: " + t.getMessage()); } }
java
{ "resource": "" }
q168930
SPFServiceRegistry.unregisterService
validation
public <T> void unregisterService(Class<? super T> serviceInterface) { Utils.notNull(serviceInterface, "serviceInterface must not be null"); ServiceValidator.validateInterface(serviceInterface, ServiceValidator.TYPE_PUBLISHED); ServiceInterface svcInterface = serviceInterface.getAnnotation(ServiceInterface.class); SPFServiceDescriptor svcDesc = ServiceInterface.Convert.toServiceDescriptor(svcInterface); String token = getAccessToken(); try { SPFError error = new SPFError(); getService().unregisterService(token, svcDesc, error); if (!error.isOk()) { handleError(error); } } catch (RemoteException e) { catchRemoteException(e); } }
java
{ "resource": "" }
q168931
SearchScheduler.generateQueryId
validation
private String generateQueryId(QueryInfo queryInfo) { String queryId = SPF.get().getUniqueIdentifier() + (++id); queryInfo.setQueryId(queryId); return queryId; }
java
{ "resource": "" }
q168932
SearchScheduler.onInstanceLost
validation
void onInstanceLost(String uniqueIdentifier) { log(TAG, "instance lost " + uniqueIdentifier); List<String> queriesIds = results.get(uniqueIdentifier); if (queriesIds == null) { return; } for (String queryId : queriesIds) { String[] args = new String[2]; args[0] = queryId; args[1] = uniqueIdentifier; Message msg = handler.obtainMessage(SearchMessages.RESULT_LOST, args); log(TAG, "sending message RESULT_LOST to handler for queryId: " + queryId); handler.sendMessage(msg); } }
java
{ "resource": "" }
q168933
SearchScheduler.stopSearch
validation
void stopSearch(String queryId) { QueryInfo info = queries.get(queryId); if(info != null){ stopSearch(info); } }
java
{ "resource": "" }
q168934
SearchScheduler.stopAllSearches
validation
void stopAllSearches(String appIdentifier) { List<QueryInfo> qinfos; synchronized (queries) { qinfos = new ArrayList<QueryInfo>(queries.values()); } for (QueryInfo queryInfo : qinfos) { if (queryInfo.getAppName().equals(appIdentifier)) { stopSearch(queryInfo); } } }
java
{ "resource": "" }
q168935
SPF.connect
validation
public static void connect(final Context context, final ConnectionListener listener) { Component.load(context, DESCRIPTOR, asBase(listener)); }
java
{ "resource": "" }
q168936
ProfileFieldViewFactory.createStandardDisplayView
validation
private <E> View createStandardDisplayView(ProfileField<E> field, E currentValue, ViewGroup viewContainer) { View result = mInflater.inflate(R.layout.profileview_field_listelement, viewContainer, false); String friendlyFieldName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profile_field_key)).setText(friendlyFieldName); String fieldValue = mHelper.convertToFriendlyString(field, currentValue); ((TextView) result.findViewById(R.id.profile_field_value)).setText(fieldValue); setUpCircleView(result, field, null); return result; }
java
{ "resource": "" }
q168937
ProfileFieldViewFactory.createSpinner
validation
private <E> View createSpinner(MultipleChoicheProfileField<E> field, E currentValue, FieldValueListener<E> listener, ViewGroup container) { View result = mInflater.inflate(R.layout.profileedit_field_multiplechoiche, container, false); String friendlyName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName); Spinner spinner = (Spinner) result.findViewById(R.id.profileedit_field_multiple_value); ArrayAdapter<E> adapter = new ArrayAdapter<E>(mContext, android.R.layout.simple_list_item_1, field.getChoiches()); spinner.setAdapter(adapter); int index = indexOf(field.getChoiches(), currentValue); if (index >= 0) { spinner.setSelection(index, false); } spinner.setOnItemSelectedListener(new OnItemSelectedAdapter<E>(field, listener, adapter)); setUpCircleView(result, field, listener); return result; }
java
{ "resource": "" }
q168938
ProfileFieldViewFactory.createDateView
validation
@SuppressWarnings("unchecked") private <E> View createDateView(final DateProfileField field, Date currentValue, final FieldValueListener<Date> listener, ViewGroup container) { View result = mInflater.inflate(R.layout.profileedit_field_date, container, false); String friendlyName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName); String dateToShow; if (currentValue == null) { dateToShow = "Click to edit"; } else { dateToShow = mHelper.convertToFriendlyString(field, currentValue); } final TextView dateTextView = (TextView) result.findViewById(R.id.profileedit_field_date_text); dateTextView.setText(dateToShow); dateTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar today = GregorianCalendar.getInstance(); int year = today.get(Calendar.YEAR); int monthOfYear = today.get(Calendar.MONTH); int dayOfMonth = today.get(Calendar.DAY_OF_MONTH); OnDateSetListener callBack = new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { GregorianCalendar cal = new GregorianCalendar(year, monthOfYear, dayOfMonth); Date newDate = new Date(cal.getTimeInMillis()); String newDateString = mHelper.convertToFriendlyString(field, newDate); dateTextView.setText(newDateString); listener.onFieldValueChanged(field, newDate); } }; DatePickerDialog dialog = new DatePickerDialog(mContext, callBack, year, monthOfYear, dayOfMonth); dialog.show(); } }); setUpCircleView(result, (ProfileField<E>) field, (FieldValueListener<E>) listener); return result; }
java
{ "resource": "" }
q168939
ProfileFieldViewFactory.createTagView
validation
@SuppressWarnings("unchecked") private <E> View createTagView(TagProfileField field, String[] currentValue, FieldValueListener<E> listener, ViewGroup container, boolean editable) { View result = mInflater.inflate(editable ? R.layout.profileedit_field_tag : R.layout.profileview_tag_field, container, false); String friendlyName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName); TagsPicker picker = (TagsPicker) result.findViewById(R.id.profileedit_tags_picker); picker.setEditable(editable); if (currentValue != null) { picker.setInitialTags(Arrays.asList(currentValue)); } if (editable) { picker.setChangeListener(new OnChangeListenerAdapter(field, (FieldValueListener<String[]>) listener)); } setUpCircleView(result, (ProfileField<E>) field, listener); return result; }
java
{ "resource": "" }
q168940
ProfileFieldViewFactory.createStandardEditView
validation
private <E> View createStandardEditView(ProfileField<E> field, E currentValue, FieldValueListener<E> listener, ViewGroup container) { View result = mInflater.inflate(R.layout.profileedit_field_standard, container, false); String friendlyName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName); EditText editText = (EditText) result.findViewById(R.id.profileedit_field_value); editText.addTextChangedListener(new OnEditorActionAdapter<>(listener, field)); if (currentValue != null) { editText.setText(mHelper.convertToFriendlyString(field, currentValue)); } setUpCircleView(result, field, listener); return result; }
java
{ "resource": "" }
q168941
SPFRemoteInstance.sendNotification
validation
public final void sendNotification(String uniqueIdentifier, SPFActionSendNotification action) { if (uniqueIdentifier == null || action == null) { throw new NullPointerException(); } String actionJSON = action.toJSON(); sendNotification(uniqueIdentifier, actionJSON); }
java
{ "resource": "" }
q168942
XmlTransformation.toXml
validation
public String toXml() { final String lqSimpleName = this.getClass().getSimpleName().toLowerCase(); final Map<String, Class<?>> aliases = new HashMap<>(); aliases.put(lqSimpleName, this.getClass()); return ObjectToXmlExtensions.toXmlWithXStream(this, aliases); }
java
{ "resource": "" }
q168943
SPFApp.setContentViewWithMinimalElements
validation
private void setContentViewWithMinimalElements() { // Set data in the RemoteViews programmatically contentView.setImageViewResource(R.id.imageView, R.drawable.ic_launcher); contentView.setTextViewText(R.id.title_text_notification, getResources().getString(R.string.notification_title)); contentView.setTextViewText(R.id.message_notification, getResources().getString(R.string.notification_text)); }
java
{ "resource": "" }
q168944
Helper.getFriendlyNameOfField
validation
public String getFriendlyNameOfField(ProfileField<?> field) { String name = getStringFromResource(PROFILE_FIELD_PREFIX + field.getIdentifier()); if(name == null){ return field.getIdentifier(); } return name; }
java
{ "resource": "" }
q168945
EternalConnect.killScheduler
validation
private void killScheduler() { if (scheduler != null) { WfdLog.d(TAG, "scheduler killed"); scheduler.shutdown(); scheduler = null; } }
java
{ "resource": "" }
q168946
SPFContext.initialize
validation
public static synchronized void initialize(Context context, int goIntent, boolean isAutonomous, ProximityMiddleware.Factory factory) { if (context == null || factory == null) { throw new NullPointerException("Arguments cannot be null"); } SPF.initialize(context, goIntent, isAutonomous, factory); sInstance = new SPFContext(); }
java
{ "resource": "" }
q168947
SPFContext.broadcastEvent
validation
public void broadcastEvent(final int code, final Bundle payload) { if (SPFConfig.DEBUG) { Log.d(TAG, "Broadcasting event " + code + " with payload " + payload); } for (final OnEventListener listener : mEventListeners) {//TODO is it thread safe? mHandler.post(new Runnable() { @Override public void run() { listener.onEvent(code, payload); } }); } }
java
{ "resource": "" }
q168948
ProfileFragment.createViewSelfProfileFragment
validation
public static ProfileFragment createViewSelfProfileFragment() { Bundle b = new Bundle(); b.putInt(EXTRA_VIEW_MODE, Mode.SELF.ordinal()); ProfileFragment fragment = new ProfileFragment(); fragment.setArguments(b); return fragment; }
java
{ "resource": "" }
q168949
ProfileFragment.onProfileDataAvailable
validation
private void onProfileDataAvailable() { Log.d(TAG, "onProfileDataAvailable"); mFactory = new ProfileFieldViewFactory(getActivity(), mMode, mCurrentPersona, mContainer); String[] mPageTitles = this.getResources().getStringArray(R.array.profileedit_fragments_titles); tabLayout.removeAllTabs(); tabLayout.addTab(tabLayout.newTab().setText(mPageTitles[0].toUpperCase(Locale.getDefault()))); tabLayout.addTab(tabLayout.newTab().setText(mPageTitles[1].toUpperCase(Locale.getDefault()))); tabLayout.addTab(tabLayout.newTab().setText(mPageTitles[2].toUpperCase(Locale.getDefault()))); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); ProfilePagerAdapter mPagerAdapter = new ProfilePagerAdapter(getChildFragmentManager(), mMode, tabLayout.getTabCount()); mViewPager.setAdapter(mPagerAdapter); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); if (mMode != Mode.SELF) { showPicture(mContainer.getFieldValue(ProfileField.PHOTO)); } else { if (getActivity() instanceof MainActivity) { ((MainActivity) getActivity()).onPhotoReady(mContainer.getFieldValue(ProfileField.PHOTO)); } else if (getActivity() instanceof ProfileViewActivity) { //TODO implement this // ((ProfileViewActivity) getActivity()).onPhotoReady(mContainer.getFieldValue(ProfileField.PHOTO)); } } // Refresh field fragments mPagerAdapter.onRefresh(); }
java
{ "resource": "" }
q168950
ProfileFragment.beginCrop
validation
public void beginCrop(Uri source) { Uri destination = Uri.fromFile(new File(this.getActivity().getCacheDir(), "cropped")); Crop.of(source, destination).asSquare().start(this.getActivity()); }
java
{ "resource": "" }
q168951
ProfileFragment.handleCrop
validation
public void handleCrop(int resultCode, Intent result) { if (resultCode == Activity.RESULT_OK) { Uri uri = Crop.getOutput(result); resultView.setImageURI(uri); InputStream inputStream = null; try { inputStream = new FileInputStream(uri.getPath()); Bitmap myBitmap = BitmapFactory.decodeStream(inputStream); myBitmap = Bitmap.createScaledBitmap(myBitmap, 130, 130, false); mContainer.setFieldValue(ProfileField.PHOTO, myBitmap); showPicture(myBitmap); } catch (FileNotFoundException e) { Log.e(TAG, "handleCrop FileInputStream-file not found from uri.getpath", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log.e(TAG, "handleCrop closing input stream error", e); } } } } else if (resultCode == Crop.RESULT_ERROR) { Toast.makeText(this.getActivity(), Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show(); } }
java
{ "resource": "" }
q168952
ObjectToJsonExtensions.toJson
validation
public static <T> String toJson(final T object, final boolean newMapper) throws JsonProcessingException { final ObjectMapper mapper = ObjectMapperFactory.getObjectMapper(newMapper); final String json = mapper.writeValueAsString(object); return json; }
java
{ "resource": "" }
q168953
TagsViewer.addTag
validation
public void addTag(String tag) { TagBubble tb = new TagBubble(getContext()); tb.setText(tag); tb.setEditable(editable); tb.setOnRemoveTagListener(bubbleClickListener); tags.add(tag.toString()); addView(tb); }
java
{ "resource": "" }
q168954
TagsViewer.setTags
validation
public void setTags(List<String> tags) { this.tags.clear(); removeAllViews(); for (String tag : tags) { addTag(tag); } }
java
{ "resource": "" }
q168955
SPFNotificationManager.saveTrigger
validation
public long saveTrigger(SPFTrigger trigger, String appPackageName) { trigger = mTriggerTable.saveTrigger(trigger, appPackageName); if (trigger != null) { if (mHandler != null) mHandler.postAddTrigger(trigger); return trigger.getId(); } else { return -1; } }
java
{ "resource": "" }
q168956
SPFNotificationManager.deleteTrigger
validation
public boolean deleteTrigger(long id, String appPackageName) { boolean success = mTriggerTable.deleteTrigger(id, appPackageName); if (success) { if (mHandler != null) mHandler.postRemoveTrigger(id); } return success; }
java
{ "resource": "" }
q168957
SPFNotificationManager.start
validation
public void start() { this.mHandlerThread = new HandlerThread("notification-handler-thread"); this.mHandlerThread.start(); this.mHandler = new SPFNotificationHandler(mHandlerThread.getLooper()); mHandler.postSetup(this); isRunning = true; }
java
{ "resource": "" }
q168958
WifiDirectMiddleware.startRegistration
validation
private void startRegistration() { // Create a string map containing information about your service. Map<String, String> mRecordMap = new HashMap<>(); mRecordMap.put(Configuration.PORT, Integer.toString(mPort)); mRecordMap.put(Configuration.IDENTIFIER, myIdentifier); // Service information. Pass it an instance name, service type // Configuration.SERVICE_REG_TYPE , and the map containing // information other devices will want once they connect to this one. WifiP2pDnsSdServiceInfo mInfo = WifiP2pDnsSdServiceInfo.newInstance( Configuration.SERVICE_INSTANCE + myIdentifier, Configuration.SERVICE_REG_TYPE, mRecordMap); // Add the local service, sending the service info, network channel, // and listener that will be used to indicate success or failure of // the request. mManager.addLocalService(mChannel, mInfo, new CustomizableActionListener( this.mContext, TAG, "Added Local Service", null, "Failed to add a service", "Failed to add a service", true)); //important: sets true to get detailed message when this method fails }
java
{ "resource": "" }
q168959
Tag.addAttribute
validation
public String addAttribute(final String name, final String value) { if (getAttributes() == null) { this.attributes = MapFactory.newLinkedHashMap(); } return getAttributes().put(name, value); }
java
{ "resource": "" }
q168960
ServiceWrapper.invokeMethod
validation
public InvocationResponse invokeMethod(InvocationRequest request) { String methodName = request.getMethodName(); if (!mMethodIndex.containsKey(methodName)) { String msg = String.format(ErrorMsg.METHOD_NOT_FOUND, methodName, mServiceDescriptor.getServiceName()); return InvocationResponse.error(msg); } Method m = mMethodIndex.get(methodName); Object[] params; try { params = deserializeParameters(request.getPayload(), m.getGenericParameterTypes()); } catch (ServiceInvocationException e) { return InvocationResponse.error("Error deserializing parameters:" + e.getMessage()); } try { Object result = m.invoke(mImplementation, params); String json = GsonHelper.gson.toJson(result); return InvocationResponse.result(json); } catch (IllegalAccessException e) { return InvocationResponse.error(e); } catch (IllegalArgumentException e) { return InvocationResponse.error(ErrorMsg.ILLEGAL_ARGUMENT); } catch (InvocationTargetException e) { return InvocationResponse.error(e.getCause()); } }
java
{ "resource": "" }
q168961
CircleSelectSpinner.setSelection
validation
public void setSelection(String[] selection) { for (String sel : selection) { for (int j = 0; j < mItems.length; ++j) { if (mItems[j].equals(sel)) { mSelection[j] = true; } } } refreshDisplayValue(); }
java
{ "resource": "" }
q168962
CircleSelectSpinner.setSelection
validation
public void setSelection(int[] selectedIndicies) { for (int index : selectedIndicies) { if (index >= 0 && index < mSelection.length) { mSelection[index] = true; } else { throw new IllegalArgumentException("Index " + index + " is out of bounds."); } } refreshDisplayValue(); }
java
{ "resource": "" }
q168963
CircleSelectSpinner.getSelectedStrings
validation
public List<String> getSelectedStrings() { List<String> selection = new LinkedList<String>(); for (int i = 0; i < mItems.length; ++i) { if (mSelection[i]) { selection.add(mItems[i]); } } return selection; }
java
{ "resource": "" }
q168964
CircleSelectSpinner.getSelectedIndicies
validation
public List<Integer> getSelectedIndicies() { List<Integer> selection = new LinkedList<Integer>(); for (int i = 0; i < mItems.length; ++i) { if (mSelection[i]) { selection.add(i); } } return selection; }
java
{ "resource": "" }
q168965
ProfileFieldsFragment.onRefresh
validation
public void onRefresh() { mViewContainer.removeAllViews(); for (ProfileField<?> field : mFieldsToShow) { View child = mParent.createViewFor(field, mViewContainer); mViewContainer.addView(child); } }
java
{ "resource": "" }
q168966
AppCommunicationAgent.shutdown
validation
public void shutdown() { synchronized (this) { if (mShutdown) { return; } for (AppServiceProxy p : mProxies.values()) { if (p.isConnected()) { mContext.unbindService(p); mProxies.remove(p); } } mShutdown = true; } }
java
{ "resource": "" }
q168967
WriterHandler.insertNewLine
validation
private void insertNewLine() throws SAXException { try { writer.write(System.getProperty("line.separator")); } catch (final IOException e) { throw new SAXException("I/O error", e); } }
java
{ "resource": "" }
q168968
WriterHandler.writeToBuffer
validation
private void writeToBuffer() throws SAXException { if (stringBuilder == null) { return; } final String string = stringBuilder.toString().trim(); write(string); stringBuilder = null; }
java
{ "resource": "" }
q168969
ObjectToJsonQuietlyExtensions.toJsonQuietly
validation
public static <T> String toJsonQuietly(final T object) { try { return ObjectToJsonExtensions.toJson(object); } catch (final JsonProcessingException e) { log.log(Level.SEVERE, "An error occured when converting object to String.\nGiven object:" + object.toString() + "\n", e); } return null; }
java
{ "resource": "" }
q168970
Component.load
validation
protected static <C extends Component<C, I>, I extends IInterface> void load(final Context context, final Descriptor<C, I> descriptor, final ConnectionCallback<C> callback) { Utils.notNull(context, "context must not be null"); Utils.notNull(descriptor, "context must not be null"); if (AccessTokenManager.get(context).hasToken()) { bindToService(context, descriptor, callback); } else { AccessTokenManager.get(context).requireAccessToken(context, new AccessTokenManager.RegistrationCallback() { @Override public void onRegistrationSuccessful() { Log.d("Component" , "Access Toekn: " + descriptor); bindToService(context, descriptor, callback); } @Override public void onRegistrationError(SPFError errorMsg) { callback.onError(errorMsg); } }); } }
java
{ "resource": "" }
q168971
Component.bindToService
validation
private static <C extends Component<C, I>, I extends IInterface> void bindToService(final Context context, final Descriptor<C, I> descriptor, final ConnectionCallback<C> callback) { Intent intent = new Intent(); intent.setComponent(SPFInfo.getSPFServiceComponentName()); intent.setAction(descriptor.getActionName()); ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder binder) { I service = descriptor.castInterface(binder); C instance = descriptor.createInstance(context, service, this, callback); callback.onServiceReady(instance); } @Override public void onServiceDisconnected(ComponentName name) { callback.onDisconnect(); } }; if (!context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) { callback.onError(new SPFError(SPFError.SPF_NOT_INSTALLED_ERROR_CODE)); } }
java
{ "resource": "" }
q168972
Component.disconnect
validation
public void disconnect() { try { mContext.unbindService(mConnection); } catch (Exception e) { Log.w(getClass().getSimpleName(), "Exception unbinding from service: ", e); } }
java
{ "resource": "" }
q168973
Component.handleError
validation
protected void handleError(SPFError err) { if (err.codeEquals(SPFError.TOKEN_NOT_VALID_ERROR_CODE)) { AccessTokenManager.get(mContext).invalidateToken(); } mCallback.onError(err); }
java
{ "resource": "" }
q168974
SPFTriggerEngine.refreshTriggers
validation
public void refreshTriggers(List<SPFTrigger> triggers2) { triggers.clear(); for (SPFTrigger trg : triggers2) { triggers.put(trg.getId(), trg); } }
java
{ "resource": "" }
q168975
ProfileTable.addPersona
validation
boolean addPersona(SPFPersona persona) { SQLiteDatabase db = getWritableDatabase(); String table = Contract.TABLE_PERSONAS; String nullColumnHack = null; ContentValues values = new ContentValues(); values.put(Contract.COLUMN_PERSONA, persona.getIdentifier()); if (db.insert(table, nullColumnHack, values) > 0) { // copy the unique identifier ProfileFieldContainer pfc = getProfileFieldBulk(SPFPersona.getDefault(), ProfileField.IDENTIFIER); String id = pfc.getFieldValue(ProfileField.IDENTIFIER); if (setValue(ProfileField.IDENTIFIER.getIdentifier(), id, persona.getIdentifier())) { addCircleToFieldsInternal(DefaultCircles.PUBLIC, ProfileField.IDENTIFIER, persona, db); addCircleToFieldsInternal(DefaultCircles.PUBLIC, ProfileField.DISPLAY_NAME, persona, db); return true; } else { removePersona(persona); return false; } } return false; }
java
{ "resource": "" }
q168976
ProfileTable.removePersona
validation
boolean removePersona(SPFPersona persona) { SQLiteDatabase db = getWritableDatabase(); if (persona.getIdentifier().equals("default")) { return false; } String table = Contract.TABLE_PERSONAS; String selection = Contract.COLUMN_PERSONA + " = ?"; String[] selectionArgs = { persona.getIdentifier() }; if (db.delete(table, selection, selectionArgs) > 0) { deleteFieldsOf(persona, db); deleteVisibilityOf(persona, db); } return true; }
java
{ "resource": "" }
q168977
ActivityConsumerRouteTable.registerService
validation
public boolean registerService(SPFServiceDescriptor descriptor) { String appId = descriptor.getAppIdentifier(); String serviceName = descriptor.getServiceName(); for (String verb : descriptor.getConsumedVerbs()) { if (!registerServiceInternal(verb, serviceName, appId)) { return false; } Log.v(TAG, "Registered service as Activity consumer: " + descriptor.getServiceName()); } return true; }
java
{ "resource": "" }
q168978
ApplicationRegistry.getAppAuthorizationByAppId
validation
AppAuth getAppAuthorizationByAppId(String appId) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ?"; String args[] = { appId }; Cursor c = mRegistryTable.getReadableDatabase().query(Contract.TABLE_NAME, null, where, args, null, null, null); AppAuth auth = null; if (c.moveToFirst()) { auth = appAuthFromCursor(c); } c.close(); return auth; }
java
{ "resource": "" }
q168979
ApplicationRegistry.registerApplication
validation
public String registerApplication(AppDescriptor descriptor, SPFPersona persona) { String token = mTokenGenerator.generateAccessToken(); ContentValues cv = new ContentValues(); cv.put(Contract.COLUMN_APP_NAME, descriptor.getAppName()); cv.put(Contract.COLUMN_ACCESS_TOKEN, token); cv.put(Contract.COLUMN_APP_IDENTIFIER, descriptor.getAppIdentifier()); cv.put(Contract.COLUMN_PERMISSION_CODE, descriptor.getPermissionCode()); cv.put(Contract.COLUMN_PERSONA, persona.getIdentifier()); SQLiteDatabase db = mRegistryTable.getWritableDatabase(); if (db.insert(Contract.TABLE_NAME, null, cv) == -1) { return null; // TODO handle insertion error } return token; }
java
{ "resource": "" }
q168980
ApplicationRegistry.unregisterApplication
validation
public boolean unregisterApplication(String appIdentifier) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ?"; String[] whereArgs = { appIdentifier }; if (mRegistryTable.getWritableDatabase().delete(Contract.TABLE_NAME, where, whereArgs) == 0) { return false; } if (SPF.get().getServiceRegistry().unregisterAllServicesOfApp(appIdentifier)) { Intent i = new Intent(DEREGISTRATION_INTENT); i.putExtra(DEREGISTERED_APP, appIdentifier); mContext.sendBroadcast(i); return true; } return false; }
java
{ "resource": "" }
q168981
ApplicationRegistry.getPersonaOf
validation
public SPFPersona getPersonaOf(String appIdentifier) { SQLiteDatabase db = mRegistryTable.getReadableDatabase(); String table = Contract.TABLE_NAME; String[] columns = { Contract.COLUMN_PERSONA }; String selection = Contract.COLUMN_APP_IDENTIFIER + " = ? "; String[] selectionArgs = { appIdentifier }; String groupBy = null; String having = null; String orderBy = null; Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy); if (c.moveToNext()) { String persona = c.getString(c.getColumnIndex(Contract.COLUMN_PERSONA)); return new SPFPersona(persona); } c.close(); return SPFPersona.DEFAULT; }
java
{ "resource": "" }
q168982
GroupOwnerActor.onMessageReceived
validation
void onMessageReceived(final WfdMessage msg) { threadPool.execute(new Runnable() { @Override public void run() { if (msg.getReceiverId().equals(myIdentifier)) { handle(msg); } else { route(msg); } } }); }
java
{ "resource": "" }
q168983
ClientsGuiList.addClientIfNotPresent
validation
public void addClientIfNotPresent(DeviceGuiElement device) { boolean add = true; for (DeviceGuiElement element : clients) { if (element != null && element.getName().equals(device.getName()) && element.getAddress().equals(device.getAddress())) { add = false; //already in the list } } if (add) { clients.add(device); } }
java
{ "resource": "" }
q168984
SPF.connect
validation
public void connect() { if (!mMiddleware.isConnected()) { mMiddleware.connect(); } if (!mNotificationManager.isRunning()) { mNotificationManager.start(); } if (mAdvertiseManager.isAdvertisingEnabled()) { mMiddleware.registerAdvertisement(mAdvertiseManager.generateAdvProfile().toJSON(), 10000); } }
java
{ "resource": "" }
q168985
ProfileFieldContainer.getFieldValue
validation
public <E> E getFieldValue(ProfileField<E> field) { if (field == null) { throw new NullPointerException(); } String val = mFields.getString(field.getIdentifier()); return val == null ? null : ProfileFieldConverter.forField(field).fromStorageString(val); }
java
{ "resource": "" }
q168986
ProfileFieldContainer.isModified
validation
public boolean isModified() { for (String key : mStatus.keySet()) { FieldStatus status = getStatus(key); if (status == FieldStatus.DELETED || status == FieldStatus.MODIFIED) { return true; } } return false; }
java
{ "resource": "" }
q168987
SPFSearch.stopSearch
validation
public void stopSearch(int tag) { String queryId = mTagToId.get(tag); mTagToId.delete(tag); if (queryId != null && mCallbacks.remove(queryId) != null) { mSearchInterface.stopSearch(queryId); } }
java
{ "resource": "" }
q168988
SPFSearch.stopAllSearches
validation
public void stopAllSearches() { mTagToId.clear(); String[] queryIds = mCallbacks.keySet().toArray(new String[]{}); mCallbacks.clear(); for (String queryId : queryIds) { mSearchInterface.stopSearch(queryId); } }
java
{ "resource": "" }
q168989
SPFSearch.lookup
validation
public SPFPerson lookup(String identifier) { boolean isReachable = mSearchInterface.lookup(identifier); if (isReachable) { return new SPFPerson(identifier); } else { return null; } }
java
{ "resource": "" }
q168990
SPFProfileManager.getProfileFieldBulk
validation
public ProfileFieldContainer getProfileFieldBulk(PersonAuth auth, SPFPersona persona, String[] fields) { return mProfileTable.getProfileFieldBulk(persona, fields, auth); }
java
{ "resource": "" }
q168991
SPFProfileManager.getBaseInfo
validation
public BaseInfo getBaseInfo(SPFPersona persona) { ProfileFieldContainer pfc = getProfileFieldBulk(persona, ProfileField.IDENTIFIER, ProfileField.DISPLAY_NAME); return new BaseInfo(pfc.getFieldValue(ProfileField.IDENTIFIER), pfc.getFieldValue(ProfileField.DISPLAY_NAME)); }
java
{ "resource": "" }
q168992
XPathExtensions.getNodeList
validation
public static NodeList getNodeList(final String xml, final String xpathExpression) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); final DocumentBuilder builder = domFactory.newDocumentBuilder(); final Document doc = builder.parse(xml); final XPath xpath = XPathFactory.newInstance().newXPath(); final XPathExpression expr = xpath.compile(xpathExpression); final Object result = expr.evaluate(doc, XPathConstants.NODESET); final NodeList nodes = (NodeList)result; return nodes; }
java
{ "resource": "" }
q168993
LooperUtils.onMainThread
validation
public static <E> E onMainThread(Class<E> callbackInterface, final E callback) { Utils.notNull(callbackInterface, "callbackInterface must not be null"); Utils.notNull(callback, "callback must not be null"); final Handler handler = new Handler(Looper.getMainLooper()); final String tag = callback.getClass().getSimpleName(); Object proxy = Proxy.newProxyInstance(callbackInterface.getClassLoader(), new Class<?>[] { callbackInterface }, new InvocationHandler() { @Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { handler.post(new Runnable() { @Override public void run() { try { method.invoke(callback, args); } catch (IllegalAccessException e) { Log.e(tag, "Error executing method " + method.getName() + " on main thread.", e); } catch (IllegalArgumentException e) { Log.e(tag, "Error executing method " + method.getName() + " on main thread.", e); } catch (InvocationTargetException e) { Log.e(tag, "Error executing method " + method.getName() + " on main thread.", e); } } }); return null; } }); return callbackInterface.cast(proxy); }
java
{ "resource": "" }
q168994
PersonPermissionTable.getPersonAuthFrom
validation
public PersonAuth getPersonAuthFrom(String receivedTkn) { if (receivedTkn.equals("")) { return PersonAuth.getPublicAuth(); } String selection = RelationshipEntry.COLUMN_TKN + " = ? AND " + RelationshipEntry.COLUMN_REQUEST_STATUS + " = ?"; String[] selectionArgs = { receivedTkn, Integer.toString(REQUEST_ACCEPTED) }; String[] columns = { RelationshipEntry.COLUMN_USER_UUID }; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(RelationshipEntry.TABLE_PERSON_AUTH, columns, selection, selectionArgs, /* groupBy */null, /* having */null, /* orderBy */ null); PersonAuth auth; if (cursor.moveToNext()) { String uniqueIdentifier = cursor.getString(cursor.getColumnIndex(RelationshipEntry.COLUMN_USER_UUID)); auth = generatePermissionFor(uniqueIdentifier, db); } else { auth = PersonAuth.getPublicAuth(); } cursor.close(); return auth; }
java
{ "resource": "" }
q168995
PersonPermissionTable.createEntryForSentRequest
validation
public String createEntryForSentRequest(String targetUid, String password) throws GeneralSecurityException { // TODO Add it back later // if (entryExistsFor(targetUid) != REQUEST_NOT_EXIST) { // return ; // } String user_uuid = targetUid; String token = new IdentifierGenerator().generateAccessToken(); int request_status = REQUEST_ACCEPTED; insertNewEntry(user_uuid, token, request_status); return TokenCipher.encryptToken(token, password); }
java
{ "resource": "" }
q168996
PersonPermissionTable.createEntryForReceivedRequest
validation
public boolean createEntryForReceivedRequest(ContactRequest fr) { String user_uuid = fr.getUserIdentifier(); String receive_token = fr.getAccessToken(); int request_status = REQUEST_PENDING; if (insertNewEntry(user_uuid, receive_token, request_status)) { return true; } return false; }
java
{ "resource": "" }
q168997
PersonPermissionTable.entryExistsFor
validation
public int entryExistsFor(String userUID) { String selection = RelationshipEntry.COLUMN_USER_UUID + " = ?"; String[] selectionArgs = { userUID }; String[] columns = { RelationshipEntry.COLUMN_REQUEST_STATUS }; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(RelationshipEntry.TABLE_PERSON_AUTH, columns, selection, selectionArgs, /* groupBy */null, /* having */null, /* orderBy */ null); if (cursor.moveToNext()) { return cursor.getInt(cursor.getColumnIndex(RelationshipEntry.COLUMN_REQUEST_STATUS)); } cursor.close(); return REQUEST_NOT_EXIST; }
java
{ "resource": "" }
q168998
PersonPermissionTable.confirmRequest
validation
public boolean confirmRequest(String targetUID, String password) throws GeneralSecurityException, WrongPassphraseException { SQLiteDatabase db = getWritableDatabase(); String table = RelationshipEntry.TABLE_PERSON_AUTH; String[] columns = { RelationshipEntry.COLUMN_TKN, RelationshipEntry.COLUMN_REQUEST_STATUS, RelationshipEntry.COLUMN_PASSWORD }; String selection = RelationshipEntry.COLUMN_USER_UUID + " = ? "; String[] selectionArgs = { targetUID }; String groupBy = null; String having = null; String orderBy = null; String limit = null; Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); if (c.moveToNext()) { String token = c.getString(c.getColumnIndex(RelationshipEntry.COLUMN_TKN)); String decryptedTkn = TokenCipher.decryptToken(token, password); if (decryptedTkn != null) { return commitConfirmation(targetUID, password, decryptedTkn); } else { return false; } } return false; }
java
{ "resource": "" }
q168999
XMLIndent.addClosingTag
validation
@Override public void addClosingTag(String tagName) { _indent.dec(); _xml.addXML(_indent.toString()); _xml.addClosingTag(tagName); _xml.addXML("\n"); }
java
{ "resource": "" }