Showing posts with label delete. Show all posts
Showing posts with label delete. Show all posts

Wednesday, February 1, 2017

How can I delete only PDF File from a folder using VBS

Option Explicit
Dim FileSystemObject, RootFolder, SubFolder, File
On Error Resume Next
 Set FileSystemObject = CreateObject("Scripting.FileSystemObject")
 RootFolder = "C:\Users\PRITOM\Downloads"
 
 For Each File In FileSystemObject.GetFolder(RootFolder).Files
  If StrComp(Right(File.Path, 4), ".pdf", vbTextCompare) = 0 Then
   Wscript.Echo File.Path + " Deleted"
   FileSystemObject.DeleteFile File.Path, True
  End If
 Next
 
 For Each SubFolder In FileSystemObject.GetFolder(RootFolder).SubFolders
 Do
  If StrComp(SubFolder.Name, "management", vbTextCompare) = 0 Then
   Exit Do
  End If
  For Each File In FileSystemObject.GetFolder(SubFolder.Path).Files
   If StrComp(Right(File.Path, 4), ".pdf", vbTextCompare) = 0 Then
    Wscript.Echo File.Path + " Deleted"
    FileSystemObject.DeleteFile File.Path, True
   End If
  Next
 Loop Until True
 Next
On Error Goto 0

Friday, November 1, 2013

How to send DELETE HTTP request in HttpURLConnection java

In a DELETE request, the parameters are sent as part of the URL and you can not send request body.
This code should get you started:

String urlParameters = "param1=1&param2=2";
String request = "http://api.server.com";
URL url = new URL(request + "?" + urlParameters); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("DELETE"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);

Print out response code and get response from server:


System.out.println("Response code: " + connection.getResponseCode());

BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line, responseText = "";
while ((line = br.readLine()) != null) {
    System.out.println("LINE: "+line);
    responseText += line;
}
br.close();
connection.disconnect();

Tuesday, July 30, 2013

Java - Call URL And Sending HTTP Parameters Via GET POST PUT PATCH DELETE Method Easily Execute

Its very easy to invoke URL using Java, We can now send GET, POST, PUT, PATCH And Delete method easily. Invoking URL in Java is easy now. Call URL and get response from that URL is can be done using Java code.

package common;

import java.io.*;
import java.lang.reflect.Field;
import java.net.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

/**
 * Created by pritom on 11/07/2016.
 */
public abstract class HttpJavaClient {    
    public static enum Method {
        GET, POST, PUT, PATCH, DELETE
    }

    public static enum Type {
        XML, JSON, URL_ENCODED;
    }
    ;

    public static void main(String[] args) throws Exception {
        Response response = doGet("https://pritomkumar.blogspot.com");
        println("Get_Result:\n" + lengthString(response.toString().replace("\n", ""), 400) + "...");

        Map params = new HashMap();
        params.put("param1", "Param1 value");
        params.put("param2", "Param2 value");

        response = doPost("https://pritomkumar.blogspot.com", buildParameters(params), Type.URL_ENCODED);
        println("Post_Result:\n" + lengthString(response.toString().replace("\n", ""), 400) + "...");
    }

    public static Response doGet(String url) {
        return execute(url, Method.GET, "", Type.URL_ENCODED);
    }

    public static Response doGet(String url, Map headers) {
        return execute(url, Method.GET, "", Type.URL_ENCODED, headers, null);
    }

    public static Response doPost(String url, String data, Type type) {
        return execute(url, Method.POST, data, type);
    }

    public static Response doPost(String url, String data, Type type, Map headers) {
        return execute(url, Method.POST, data, type, headers, null);
    }

    public static Response doPut(String url, String data, Type type) {
        return execute(url, Method.PUT, data, type);
    }

    public static Response doPut(String url, String data, Type type, Map headers) {
        return execute(url, Method.PUT, data, type, headers, null);
    }

    public static Response doPatch(String url, String data, Type type) {
        return execute(url, Method.PATCH, data, type);
    }

    public static Response doPatch(String url, String data, Type type, Map headers) {
        return execute(url, Method.PATCH, data, type, headers, null);
    }

    public static Response doDelete(String url) {
        return execute(url, Method.DELETE, "", Type.URL_ENCODED);
    }

    public static Response doDelete(String url, Map headers) {
        return execute(url, Method.DELETE, "", Type.URL_ENCODED, headers, null);
    }

    public static Response execute(String url, Method method, String data, Type type) {
        return execute(url, method, data, type, null, null);
    }

    private static Response execute(String requestURL, Method requestMethod, String requestData, Type dataType, Map headers, Integer timeOutMilli) {
        Long started = System.currentTimeMillis();
        String httpResponse = "", responseMessage = "";
        Integer httpCode = 0;
        timeOutMilli = timeOutMilli == null ? 1000 * 30 : timeOutMilli; /* Default read & write timeout */

        HttpsURLConnection connection = null;
        try {
            String contentType = "", accept = "", contentLength = "" + requestData.length();
            switch (dataType) {
                case XML:
                    contentType = "text/xml; charset=utf-8";
                    accept = "text/xml";
                    break;
                case JSON:
                    contentType = "application/json";
                    break;
                case URL_ENCODED:
                    contentType = "application/x-www-form-urlencoded";
                    break;
            }

            connection = (HttpsURLConnection) new URL(requestURL).openConnection();
            setRequestMethod(connection, requestMethod.name());
            connection.setDoOutput(true);
            connection.setConnectTimeout(timeOutMilli);
            connection.setReadTimeout(timeOutMilli);
            connection.setRequestProperty("Pragma", "no-cache");

            if (headers != null && headers.size() > 0) {
                for (Object name : headers.keySet().toArray()) {
                    if (name.toString().endsWith("tls")) {
                        //headers.put("tls", "TLSv1.2");
                        //headers.put("tls", "TLSv1");
                        SSLContext sc = SSLContext.getInstance(headers.get(name.toString()).toString());
                        sc.init(null, null, new java.security.SecureRandom()); 
                        connection.setSSLSocketFactory(sc.getSocketFactory());
                    }
                    else {
                        connection.setRequestProperty(name.toString(), headers.get(name.toString()).toString());
                    }
                }
            }

            if (requestData.length() > 0) {
                connection.setDoInput(true);

                if (accept.length() > 0) {
                    connection.setRequestProperty("Accept", accept);
                }
                if (contentType.length() > 0) {
                    connection.setRequestProperty("Content-Type", contentType);
                }

                connection.setRequestProperty("Content_length", contentLength);
                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                writer.write(requestData);
                writer.flush();
                writer.close();
            }

            httpCode = connection.getResponseCode();
            responseMessage = connection.getResponseMessage();
            InputStream is = null;

            if (httpCode >= 200 && httpCode <= 299) {
                is = connection.getInputStream();
            }
            else {
                is = connection.getErrorStream();
            }

            Writer writer5 = new StringWriter();
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer5.write(buffer, 0, n);
                }
                httpResponse = writer5.toString();
            }
            catch (Exception ex) {
                httpResponse = "";
                responseMessage = ex.getMessage();
            }
        }
        catch (Exception ex) {
            httpResponse = "";
            responseMessage = ex.getMessage();
        }
        finally {
            try {
                connection.disconnect();
            }
            catch (Exception ex10) {
            }
        }

        return new Response(requestURL, httpCode, responseMessage, httpResponse, (System.currentTimeMillis() - started));
    }

    /* JAVA - HttpURLConnection Invalid HTTP method such as 'PATCH' */
    private static void setRequestMethod(final HttpsURLConnection httpURLConnection, final String method) throws Exception {
        try {
            httpURLConnection.setRequestMethod(method);
        }
        catch (final ProtocolException pe) {
            Class<?> connectionClass = httpURLConnection.getClass();
            Field delegateField = null;
            try {
                delegateField = connectionClass.getDeclaredField("delegate");
                delegateField.setAccessible(true);
                HttpsURLConnection delegateConnection = (HttpsURLConnection) delegateField.get(httpURLConnection);
                setRequestMethod(delegateConnection, method);
            }
            catch (NoSuchFieldException e) {
                // Ignore for now, keep going
            }
            catch (IllegalArgumentException e) {
                throw new RuntimeException(e);
            }
            catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            try {
                Field methodField;
                while (connectionClass != null) {
                    try {
                        methodField = connectionClass.getDeclaredField("method");
                    }
                    catch (NoSuchFieldException e) {
                        connectionClass = connectionClass.getSuperclass();
                        continue;
                    }
                    methodField.setAccessible(true);
                    methodField.set(httpURLConnection, method);
                    break;
                }
            }
            catch (final Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static String buildParameters(Map parametersMap) {
        Iterator nameIterator = parametersMap.keySet().iterator();
        StringBuffer buf = new StringBuffer();

        while (nameIterator.hasNext()) {
            Object key = nameIterator.next();
            Object value = parametersMap.get(key);
            if (value == null) {
                value = "";
            }

            if (!(key instanceof String)) {
                throw new IllegalArgumentException("Expected a string key in parametersMap but found " + key);
            }

            if (!(value instanceof String)) {
                throw new IllegalArgumentException("Expected a string value in parametersMap but found " + value);
            }

            String parameterName = (String) key;
            String parameterValue = (String) value;
            if (buf.length() > 0) {
                buf.append('&');
            }

            try {
                buf.append(parameterName);
                buf.append('=');
                buf.append(URLEncoder.encode(parameterValue, "UTF-8"));
            }
            catch (Exception var9) {
                var9.printStackTrace();
            }
        }

        return buf.toString();
    }

    public static void parseParameters(String s, String enc, Map parameters) {
        if (s != null) {
            int start = 0;
            int end = s.length();
            boolean amp = true;

            do {
                int amp1 = s.indexOf(38, start);
                if (amp1 == -1) {
                    amp1 = end;
                }

                int eq = s.indexOf(61, start);
                if (eq == -1 || eq > amp1) {
                    eq = amp1;
                }

                String name = s.substring(start, eq);
                String value = eq == amp1 ? "" : s.substring(eq + 1, amp1);

                try {
                    parameters.put(URLDecoder.decode(name, enc), URLDecoder.decode(value, enc));
                }
                catch (Exception var11) {
                    var11.printStackTrace();
                }

                start = amp1 + 1;
            } while (start < end);
        }
    }

    public static class Response {
        private String url;
        private Integer code;
        private String message;
        private String body;
        private Long time;

        public Response(String url, Integer code, String message, String body, Long time) {
            this.url = url;
            this.code = code;
            this.message = message;
            this.body = body;
            this.time = time;
        }

        @Override
        public String toString() {
            return "{URL=" + this.url + ",Code=" + this.code + ", Message=" + this.message + ", Time=" + this.time + " Millis, Body=" + this.body + "}";
        }

        public Integer getCode() {
            return this.code;
        }

        public String getMessage() {
            return this.message;
        }

        public String getBody() {
            return this.body;
        }

        public Long getTime() {
            return this.time;
        }
    }

    public static void println(Object o) {
        System.out.println("" + o);
    }

    public static String lengthString(String s, Integer m) {
        return s.length() > m ? s.substring(0, m) : s;
    }
}

Monday, June 3, 2013

jQuery delete a given key from array

When I have an array like this:
  1. var test = Array();
  2. test['key1'] = 'value1';
  3. test['key2'] = 'value2';
I believe the delete operator in JavaScript will solve this:
  1. var test = new Array();
  2. test['key1'] = 'value1';
  3. test['key2'] = 'value2';
  4. delete test['key1']; // will remove key1 from the array

Tuesday, April 23, 2013

Android sdk create and update and delete contact

The following permissions need to handle contacts on android application:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" /> 

And import of 
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.RawContacts;
import android.provider.MediaStore;
are also important.
 
/* CREATE A NEW CONTACT */
String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.Contacts.STARRED,
        ContactsContract.Contacts.TIMES_CONTACTED,
        ContactsContract.Contacts.CONTACT_PRESENCE,
        ContactsContract.Contacts.PHOTO_ID,
        ContactsContract.Contacts.LOOKUP_KEY,
        ContactsContract.Contacts.HAS_PHONE_NUMBER,
    };
ArrayList<ContentProviderOperation> ops5 = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops5.size();

Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
builder.withValue(RawContacts.ACCOUNT_TYPE, null);
builder.withValue(RawContacts.ACCOUNT_NAME, null);
ops5.add(builder.build());

// Name
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "Pritom"+ " " +"Kumar");
ops5.add(builder.build());

// Number
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "01727499452");
builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
ops5.add(builder.build());

// Picture
try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(r.getPhoto()));
    ByteArrayOutputStream image = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG , 100, image);
    builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
    builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex);
    builder.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
    builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
    ops.add(builder.build());
}
catch (Exception e)
{
    e.printStackTrace();
}

// Add the new contact
try
{
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops5);
}
catch (Exception e)
{
    e.printStackTrace();
}
String select = "(" + ContactsContract.Contacts.DISPLAY_NAME + " == \"" +Pritom+ " " +"Kumar"+ "\" )";
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
startManagingCursor(c);

if (c.moveToNext())
{
    System.out.println("NEW ID: "+c.getString(0));
}

/* UPDATE CONTACT BY RAW ID */
int id = 2;
String firstname = "Pritom";
String lastname = "Kumar";
String number = "01727499452";
String photo_uri = "android.resource://com.my.package/drawable/default_photo";

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

// Name
builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?", new String[]{String.valueOf(id), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE});
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, lastname);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstname);
ops.add(builder.build());
// Number
builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?"+ " AND " + ContactsContract.CommonDataKinds.Organization.TYPE + "=?", new String[]{String.valueOf(id), ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)});
builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number);
ops.add(builder.build());
// Picture
try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse(photo_uri));
    ByteArrayOutputStream image = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG , 100, image);

    builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
    builder.withSelection(ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?", new String[]{String.valueOf(id), ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE});
    builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
    ops.add(builder.build());
}
catch (Exception e)
{
    e.printStackTrace();
}
try
{
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (Exception e)
{
    System.out.println(e.getMessage());
}

/* DELETE CONTACT BY RAW CONTACT ID AND CONTACT ID */
Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID +" = ?", new String[]{"3"}, null);
Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{"3"}, null);
while (pCur.moveToNext())
{
    String lookupKey = pCur.getString(pCur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
    getContentResolver().delete(uri, null, null);
}

Friday, February 1, 2013

php array delete by value (not key)

Using array_seach(), try the following:
if(($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a "falsey" value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.
The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

Friday, January 18, 2013

Cakephp delete and update records by conditions

Delete Records:
$this->ModelName->deleteAll(
    array(
        "ModelName.id" => 10
    )
);

Update Records:
$this->ModelName->updateAll(
    /* UPDATE FIELD */
    array(
        "ModelName.is_active" => 0,
    ),
    /* CONDITIONS */
    array(
        "ModelName.id" => 20,
        "ModelName.name LIKE" => '%SEARCH_TEXT%',
        "ModelName.name <>" => 'NOT_EQUAL_VALUE',
        'ModelName.integer_field > ' => 50, [Can use operand here]
        'TIMESTAMPDIFF(DAY, ModelName.date, NOW())' => 22 [number of day]
    )
);

Tuesday, May 15, 2012

Execute Curl to GET POST PUT PATCH DELETE Method Using Php

$headers[] = "Authorization: Basic xxx";
$headers[] = "Accept: text/xml";

$post = array(
    "name" => "Some name",
    "roll" => "Some roll"

);

$result = CurlExecutor::execute("...com/api/test", "POST", $post, null, $headers);
CurlExecutor::prettyPrint($result);


<?php
class CurlExecutor
{
    static function execute($url, $method = "GET", $posts = null, $gets = null, $headers = null, Closure $closure = null)
    {
        $ch = curl_init();
        if ($gets != null) {
            $url .= "?" . (is_array($gets) ? self::makeRawQuery($gets) : $gets);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($posts != null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($posts) ? self::makeRawQuery($posts) : $posts);
        }
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, true);
        } else if ($method == "HEAD") {
            curl_setopt($ch, CURLOPT_NOBODY, true);
        } else if ($method == "PUT" || $method == "BATCH" || $method == "DELETE") {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        }
        if (!is_null($headers) && is_array($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if (!is_null($closure)) {
            $closure($ch);
        }
        $response = curl_exec($ch);
        if ((curl_errno($ch) == 60)) {
            /* Invalid or no certificate authority found - Retrying without ssl */
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $response = curl_exec($ch);
        }
        /* If you want to retry on failed status code */
        $retryCodes = array('401', '403', '404');
        $retries = 0;
        $retryCount = 3;
        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (in_array($httpStatus, $retryCodes)) {
            do {
                $response = curl_exec($ch);
                $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            } while (in_array($httpStatus, $retryCodes) && (++$retries < $retryCount));
        }
        if (curl_errno($ch)) {
            $response = curl_error($ch);
        }
        curl_close($ch);
        return array(
            "code" => $httpStatus,
            "response" => $response
        );
    }

    static function makeRawQuery($data, $keyPrefix = "")
    {
        $query = "";
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (strlen($keyPrefix) > 0) {
                    $keyPrefixDummy = $keyPrefix . "[" . $key . "]";
                } else {
                    $keyPrefixDummy = $key;
                }
                $query = $query . self::makeRawQuery($value, $keyPrefixDummy);
            } else {
                if (strlen($keyPrefix) > 0) {
                    $key = $keyPrefix . "[" . $key . "]";
                }
                $query .= $key . "=" . rawurlencode($value) . "&";
            }
        }
        return rtrim($query, "&");
    }

    static function prettyPrint($o)
    {
        echo "<pre>";
        print_r($o);
        echo "</pre>";
    }
}