Monday, July 18, 2016

Salesforce create custom controller

1. Go to "setup/Develop/Apex Classes" and click "new"
2. Write the following code:


public class CustomController {

    public Account account { get; private set; }

    public NewAndExistingController() {
        Id id = ApexPages.currentPage().getParameters().get('id');
        account = (id == null) ? new Account() :
            [SELECT Name, Phone, Industry FROM Account WHERE Id = :id];
    }

    public PageReference save() {
        try {
            upsert(account);
        } 
        catch(System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }
        //  After successful Save, navigate to the default view page
        PageReference r = new ApexPages.StandardController(Account).view();
        return (r);
    }
}


3. Go to "setup/Develop/Visualforce Pages" and click "new"
4. Write the following code:

<apex:page controller="CustomController" tabstyle="Account">
    <apex:form>
        <apex:pageBlock mode="edit">
            <apex:pageMessages/>
            <apex:pageBlockSection>
                <apex:inputField value="{!Account.name}"/>
                <apex:inputField value="{!Account.phone}"/>
                <apex:inputField value="{!Account.industry}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Save" action="{!save}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

5. Go to "setup/Create/Tabs" click on "new" under group "Visualforce Tabs"
6. Select "Visualforce Page" created before & provide other information & save.

7. Browse your custom tab to access the custom tab.


Show HTML string as an HTML output instead of plain text in Salesforce Visaul Force page

Write the following code snippet:


<apex:outputLabel escape="false" Value="{!html}" ></apex:outputLabel>


Instead of the following:

{!html} 

How to make a post or get request to some other server from apex class

1. Go to "setup/Develop/Apex Class"
2. Click "new"
3. Write code as following:


public class ApexClass_1 {
    @Future(callout=true)
    public static void c1(String Account_ID) {
        String name = '';
        try {
            HttpRequest req = new HttpRequest();
            req.setEndpoint('http://www.yahoo.com');
            req.setMethod('POST');
            req.setBody('Account_ID='+EncodingUtil.urlEncode(Account_ID, 'UTF-8')+'&other_param='+EncodingUtil.urlEncode('OTHER PARAM VALUE', 'UTF-8'));
            req.setCompressed(true);

            /* If you want to send basic authentication */
            String username = 'myname';
            String password = 'mypwd';
            Blob headerValue = Blob.valueOf(username + ':' + password);
            String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
            req.setHeader('Authorization', authorizationHeader);

            Http http = new Http();
            HTTPResponse res = http.send(req);
            name = 'Status_Code=' + res.getStatusCode();
            String responseBody = res.getBody();
        }
        catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
            name = ('Error=' + e.getMessage()).substring(0, 20);
        }

        /* Reading account object */
        Account account = [SELECT Id FROM Account WHERE Id = :Account_ID];
        account.Name = name;
        update op;
    }
}


4. Go to "setup/Security Controls/Remote Site Settings"
5. Click "New remote site" & enter the URL that you want to invoke from apex class.
6. Invoke method "ApexClass_1.c1" from wherever you want.

7. An example of invoke url in salesforce from apex sObjects trigger options
8. Go to "setup/Customize/Accounts/Triggers"
9. Click "new"
10. Write the following code:

trigger TriggerActionName on Account (before insert, after insert, after delete) {
    if (Trigger.isInsert) {
        if (Trigger.isAfter) {
            for (Account a : Trigger.New) {
                ApexClass_1.c1(a.Id);
            }
        }
    }
}


11. Once you create a new account the url would be invoked in a short time (Also you could write code for update & delete)
12. Apex trigger documentation: https://developer.salesforce.com/trailhead/en/apex_triggers/apex_triggers_intro

Tuesday, June 28, 2016

Java Convert File Into Bytes (Array of Bytes)


package com.pritom.kumar;

import java.io.File;
import java.io.FileInputStream;

/**
 * Created by pritom on 28/06/2016.
 */
public class ReadFileAsByteArray {
    public static void main (String[] args) throws Exception {
        File file = new File("x1.zip");

        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        System.out.println("File_Length=" + file.length() + ", Byte_Length=" + toByte.length + ", Both_Are_Equal=" + (file.length() == toByte.length ? "True" : "False"));
    }
}


Output:

File_Length=14805774, Byte_Length=14805774, Both_Are_Equal=True

Java code to compress & decompress of string using deflater & inflater

Code snippet for compress & decompress of string...

package com.pritom.kumar;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * Created by pritom on 27/06/2016.
 */
public class CompressString {
    public static final String encoding = "UTF-8";

    public static void main (String[] args) throws Exception {
        String s = "123456789 a s d f g h j k l ; ' q w e r t y u i o p [ ] \\ 1 2 3 4 5 6 7 8 9 0 - = as df gh jk l; zx cv bn m, ./ qw y ui op []" +
                "qwe rty uio p[] asd fgh jkl zxc vbn m,. 123 456 789 1234 5678 90-= qwer tyui op[] asdf ghjk l;zx cvbn m,./" +
                "12345 67890 qwert yuiop asdfg hjklz xcvbn m,khg er xcgvdst 453 gd fyrt634 5 dg e653 545u7r ydf dgfsd fsart sdgdsg" +
                "sd fsdjf;sjduw[r sldfjsl;djrf2345203v sdfs'wse[rftu 2[3r50 j;lgjks'drf 2354-0u sadfas';dfmka][ ert02u9wsd's;lad fa'sdfjasdgf" +
                "4 wr[w09u jsd' af32 'QWRJE ajfsdj :ejwkiiuUUSJ W[9230 U'SFJKS JFJSF 'ASDP;GF SDFAW435]2 JKSD';GDALSJ GF'SDAGJFMA'L 2UWQ 'PS;DGJM" +
                "ju=[0a9 u0wr w435r]2345ru]2tu  s'adgjfa'sgf2uq]34u]23'g jfq4323o4 23w 52]5-2t4ewsjtrg'qwpe[fa7 2   03r/ dshgf" +
                "djl3r4 sjdf ;wq3r q3ra[d0aw'tj3 wr[w09u asd fgh zxc er gd swser9[0345r]2 3dfjsdfsd ]23-qg';gvas 'dgawejrt ]23trwasdg;mas'fgsnkd gasf " +
                "[w90rtusdmgkf zxc sadfs fa fsart sdgdsg wr JFJSF GF fgh xcgvdst dfmka SDAGJFMA 2345ru wse[rftu 2[3r50 j;l af32 sdfjasdgf jks'drf 2354-" +
                "djrf2345203v KSD';GDALSJ GF'";

        String compressed = compress(s);
        Integer savedLength = s.length() - compressed.length();
        Double saveRatio = (new Double(savedLength) * 100) / s.length();
        String ratioString = saveRatio.toString() + "00000000";
        ratioString = ratioString.substring(0, ratioString.indexOf(".") + 4);
        println("Original_String_Length=" + s.length());
        println("Compressed_String_Length=" + compressed.length() + ", Compression_Ratio=" + ratioString + "%");

        String decompressed = decompress(decodeBase64(compressed));
        println("Decompressed_String_Length=" + decompressed.length() + " == Original_String_Length (" + s.length() + ")");
        println("Original_String == Decompressed_String=" + (s.equals(decompressed) ? "True" : "False"));
    }

    public static String compress(String str) throws Exception {
        return compress(str.getBytes(encoding));
    }

    public static String compress(byte[] bytes) throws Exception {
        Deflater deflater = new Deflater();
        deflater.setInput(bytes);
        deflater.finish();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
        byte[] buffer = new byte[1024];
        while(!deflater.finished()) {
            int count = deflater.deflate(buffer);
            bos.write(buffer, 0, count);
        }
        bos.close();
        byte[] output = bos.toByteArray();
        return encodeBase64(output);
    }

    public static String decompress(byte[] bytes) throws Exception {
        Inflater inflater = new Inflater();
        inflater.setInput(bytes);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
        byte[] buffer = new byte[1024];
        while (!inflater.finished()) {
            int count = inflater.inflate(buffer);
            bos.write(buffer, 0, count);
        }
        bos.close();
        byte[] output = bos.toByteArray();
        return new String(output);
    }

    public static String encodeBase64(byte[] bytes) throws Exception {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encodeBuffer(bytes).replace("\r\n", "").replace("\n", "");
    }

    public static byte[] decodeBase64(String str) throws Exception {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        return base64Decoder.decodeBuffer(str);
    }

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

Output would be like this...

Original_String_Length=1000
Compressed_String_Length=824, Compression_Ratio=17.600%
Decompressed_String_Length=1000 == Original_String_Length (1000)
Original_String == Decompressed_String=True

** More big string more compression ratio
** More similar words more compression ratio

Ideone link

Wednesday, May 25, 2016

Grails create read only service

Full read only service


package com.pkm.services.common

import org.springframework.transaction.annotation.Transactional

@Transactional(readOnly = true)
class DataReadService {
    def a() {

    }

    def b() {

    }
}

Some methods (method a) are read only, others are transactional


package com.pkm.services.common

import org.springframework.transaction.annotation.Transactional

@Transactional
class DataReadService {
    @Transactional(readOnly = true)
    def a() {

    }

    def b() {

    }
}