LoginFailed on connecting outlook 365 - jakarta-mail

package com.email.test;
import java.util.Arrays;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class SampleEmailReader {
public static final int SUCCESS = 0;
public static final int FAILURE = -1;
private transient static final Logger logger = LoggerFactory.getLogger(SampleEmailReader.class);
public SampleEmailReader() {
}
public void processEmailAttachements() {
try {
logger.info("Started processEmailAttachements ");
Properties emailProperties = new Properties();
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
emailProperties.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
emailProperties.setProperty("mail.imaps.socketFactory.fallback", "false");
emailProperties.setProperty("mail.imaps.port", "993");
emailProperties.setProperty("mail.imaps.socketFactory.port", "993");
emailProperties.setProperty("mail.imaps.auth", "true");
emailProperties.setProperty("mail.imaps.host", "outlook.office365.com");
emailProperties.setProperty("mail.imaps.auth.plain.disable", "true");
emailProperties.setProperty("mail.imaps.auth.gssapi.disable", "true");
emailProperties.setProperty("mail.imaps.auth.ntlm.disable", "true");
emailProperties.setProperty("mail.imaps.ssl.enable", "true");
Session session = Session.getInstance(emailProperties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("test#outlook.com", "password#2016");
}
});
Store store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
logger.info("Inbox MessageCount-->" + inbox.getMessageCount());
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
logger.info("Number of UnRead Mails = " + messages.length);
for (Message inboxMessage : messages) {
int status = processMessageBody(inboxMessage);
if (status == SUCCESS) {
inboxMessage.setFlag(Flag.SEEN, true);
} else {
inboxMessage.setFlag(Flag.SEEN, false);
}
}
inbox.close(true);
store.close();
} catch (Exception ex) {
ex.printStackTrace();
logger.error("Error in processEmailAttachements", ex);
}
}
private int processMessageBody(Message message) {
int status = FAILURE;
try {
logger.info("Started processMessageBody*******");
logger.info("Message Subject******" + message.getSubject());
logger.info("From Address *******"
+ Arrays.toString(message.getFrom()));
Object content = message.getContent();
if (content instanceof String) {
logger.error("Invalid Content Type.No need to process the Mail with Subject "
+ message.getSubject());
} else if (content instanceof Multipart) {
Multipart multiPart = (Multipart) content;
try {
for (int i = 0; i < multiPart.getCount(); i++) {
BodyPart bodyPart = multiPart.getBodyPart(i);
if (bodyPart.getDisposition() != null
&& bodyPart.getDisposition().equalsIgnoreCase(
Part.ATTACHMENT)
&& bodyPart.getFileName() != null) {
status = readExcel(bodyPart);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("BatchException in procesMultiPart", e);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception in processMessageBody", e);
}
return status;
}
public abstract int readExcel(BodyPart bodyPart);
}
Executing
package EmailTable;
import javax.mail.BodyPart;
public class Email {
public static void main(String[] args) {
// TODO Auto-generated method stub
SampleEmailReader reader = new SampleEmailReader() {
#Override
public int readExcel(BodyPart bodyPart) {
// TODO Auto-generated method stub
return 0;
}
};
reader.processEmailAttachements();
}
}
Getting Autheticate Failed.. But username password is correct. and i am able to login outlook 365 with the username and password. ONLY difference I am seeing there is certitificate displayed on the browser.. Do I need to use any certificate to read the mail?
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect

Related

Incompatible types. Found: 'java.util.ArrayList<java.lang.Object>', required: 'java.util.ArrayList<UserLocation>'

So I am creating a route planner app in Android Studio and its giving me the error in the title of this question
Heres my code
import android.Manifest;
import android.app.Fragment;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.example.destinationrouteplanner.R;
import com.example.destinationrouteplanner.adapters.UserRecyclerAdapter;
import com.example.destinationrouteplanner.models.MarkerCluster;
import com.example.destinationrouteplanner.models.User;
import com.example.destinationrouteplanner.util.MyClusterManagerRenderer;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.maps.android.clustering.ClusterManager;
import java.util.ArrayList;
public class UserListFragment extends Fragment implements OnMapReadyCallback
{
private static final String TAG = "UserListFragment";
private RecyclerView mUserListRecyclerView;
private MapView mMapView;
private ArrayList<User> mUserList = new ArrayList<>();
//private UserRecyclerAdapter mUserRecyclerAdapter;
private ArrayList<UserLocation> mUserLocations = new ArrayList<>();
private UserRecyclerAdapter mUserRecyclerAdapter;
private GoogleMap mGoogleMap;
private LatLngBounds mMapBoundary;
private UserLocation mUserPosition;
private ClusterManager mClusterManager;
private MyClusterManagerRenderer mClusterManagerRenderer;
private ArrayList<MarkerCluster> mClusterMarkers = new ArrayList<>();
public static UserListFragment newInstance() {
return new UserListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mUserList = getArguments().getParcelableArrayList(getString(R.string.intent_user_list));
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_list, container, false);
mUserListRecyclerView = view.findViewById(R.id.user_list_recycler_view);
mMapView = view.findViewById(R.id.user_list_map);
initUserListRecyclerView();
initGoogleMap(savedInstanceState);
return view;
}
private void initGoogleMap(Bundle savedInstanceState){
// *** IMPORTANT ***
// MapView requires that the Bundle you pass contain _ONLY_ MapView SDK
// objects or sub-Bundles.
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
}
mMapView.onCreate(mapViewBundle);
mMapView.getMapAsync(this);
}
private void initUserListRecyclerView() {
mUserRecyclerAdapter = new UserRecyclerAdapter(mUserList);
mUserListRecyclerView.setAdapter(mUserRecyclerAdapter);
mUserListRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mMapView.onSaveInstanceState(mapViewBundle);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onStart() {
super.onStart();
mMapView.onStart();
}
#Override
public void onStop() {
super.onStop();
mMapView.onStop();
}
#Override
public void onMapReady(GoogleMap map) {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
mGoogleMap = map;
addMapMarkers();
}
#Override
public void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
private void addMapMarkers()
{
if (mGoogleMap !=null)
{
if(mClusterManager == null)
{
mClusterManager = new ClusterManager<MarkerCluster>(getActivity().getApplicationContext(), mGoogleMap);
}
if (mClusterManagerRenderer == null)
{
mClusterManagerRenderer = new MyClusterManagerRenderer(getActivity(), mGoogleMap, mClusterManager);
mClusterManager.setRenderer(mClusterManagerRenderer);
}
for (UserLocation userLocation: mUserLocations)
{
Log.d(TAG, "AddMapMarkers: location: " + userLocation.getGeo_point().toString());
try {
String snippet = "";
if (userLocation.getUser().getUser_id().equals(FirebaseAuth.getInstance().getUid()))
{
snippet = "This is you";
}else {
snippet = "Determine route to " + userLocation.getUser().getUsername() + "?";
}
int avatar = R.drawable.cwm_logo; //Set the default avatar
try {
avatar = Integer.parseInt(userLocation.getUser().getAvatar());
}catch (NumberFormatException e)
{
Log.d(TAG, "addMapMarkers: no avatar for: " + userLocation.getUser().getUsername() + ", setting default");
}
MarkerCluster newMarkerCluster = new MarkerCluster(new LatLng(userLocation.getGeo_point().getLatitude(), userLocation.getGeo_point().getLongitude(), userLocation.getUser().getUsername(), snippet, avatar, userLocation.getUser()));
mClusterManager.addItem(newMarkerCluster);
mClusterMarkers.add(newMarkerCluster);
}catch (NullPointerException e)
{
Log.e(TAG "addMapMarkers: NullPointerException: " + e.getMessage());
}
}
mClusterManager.cluster();
setCameraView();
}
}
private void setCameraView()
{
double bottomBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double leftBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
double topBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double rightBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
}
}
I tired using the answer to this question but not working
Required type:
ArrayList
Provided:
ArrayList
no instance(s) of type variable(s) exist so that UserLocation conforms to Object

Apache Camel hanging/locking up - threadsafe issue?

Very old project I have 'inherited', Apache 2.2.0 and apparently has never 'worked right'.
The process seems to 'lock up' occasionally and never completes. If the process is killed, files moved back to inbound, and restarted it seems to work. So it's a weird intermittent problem.
I believe the issue may be due to a custom RoutePolicy implementation;
package com.company.integration.management;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Route;
import org.apache.camel.SuspendableService;
import org.apache.camel.component.seda.SedaEndpoint;
import org.apache.camel.impl.ThrottlingInflightRoutePolicy;
import org.apache.log4j.Logger;
public class ParserInflightRoutePolicy extends ThrottlingInflightRoutePolicy {
private static Route fileRoute;
private static final int MAX_FILES_INFLIGHT = 3;
private static final int MSG_HIGH_WATERMARK = 100;
private static final int MSG_LOW_WATERMARK = 25;
private Logger logger = Logger.getLogger(getClass());
#Override
public void onExchangeBegin(Route route, Exchange exchange) {
int sedaMessagesInflight = 0;
sedaMessagesInflight = sedaQueueSize(route);
if (route.getId().equalsIgnoreCase("initialRoute")) {
fileRoute = route;
try {
if ((sedaQueueSize(route, "seda://parser") >= MAX_FILES_INFLIGHT) || (sedaMessagesInflight >= MSG_HIGH_WATERMARK)) {
if ( ! ((SuspendableService)fileRoute.getConsumer()).isSuspended() ) {
logger.error("FLOW CONTROL: stop file component");
((SuspendableService)fileRoute.getConsumer()).suspend();
}
}
}
catch (Exception ex) {
logger.error("Error stopping route", ex);
}
}
if (route.getId().equalsIgnoreCase("pricingRoute") || route.getId().equalsIgnoreCase("persistenceRoute")) {
try {
if ((sedaQueueSize(route, "seda://parser") == 0) && (sedaMessagesInflight <= MSG_LOW_WATERMARK)) {
if ( ((SuspendableService)fileRoute.getConsumer()).isSuspended() ) {
logger.error("FLOW CONTROL: start file component");
((SuspendableService)fileRoute.getConsumer()).resume();
}
}
}
catch (Exception ex) {
logger.error("Error starting route", ex);
}
}
}
int sedaQueueSize(Route route) {
int sedaMessagesInflight = 0;
CamelContext camelContext = route.getRouteContext().getCamelContext();
for (Route rte : camelContext.getRoutes()) {
Endpoint endpoint = rte.getEndpoint();
if (endpoint instanceof SedaEndpoint) {
SedaEndpoint seda = (SedaEndpoint)endpoint;
if (seda.getQueue().size() > 0) {
sedaMessagesInflight += seda.getQueue().size();
}
}
}
logger.debug("SEDA messages inflight [" + sedaMessagesInflight + "]");
return sedaMessagesInflight;
}
int sedaQueueSize(Route route, String endPointUri) {
CamelContext camelContext = route.getRouteContext().getCamelContext();
Endpoint endpoint = camelContext.getEndpoint(endPointUri);
if (endpoint instanceof SedaEndpoint) {
return ((SedaEndpoint) endpoint).getQueue().size();
}
return 0;
}
#Override
public void onExchangeDone(Route route, Exchange exchange) {
;
}
}
Notice that this code does not appear to be threadsafe - no locking mechanism as implemented in ThottlingInflightRoutePolicy. Could this be causing the intermittent issue?

how to export and import realm data in android

I know there are those questions which are similar to mine have already raised.
However, I can not go further more on some point.
** I can not copy file on below.-> realm.writeCopyTo(exportRealmFile);
** The code that I referred to is below.
https://stackoverflow.com/a/36324183/6650123
And let me share my application class which I defaulted Realm.
Wondering if the realm file can not be copied because of that..
Would you take a look and advise?
**
public class MyApplication extends Application {
private static MyApplication singleton;
private RealmConfiguration realmConfig;
String TAG=getClass().getName();
public static MyApplication getSingleton(){;
return singleton;
}
public void onCreate() {
super.onCreate();
singleton=this;
// Create the Realm configuration
realmConfig = new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(realmConfig);
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void onLowMemory() {
super.onLowMemory();
}
public void onTerminate() {
super.onTerminate();
}
}
// my codes for backup realm
package com.first.project;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import io.realm.Realm;
public class RealmBackupRestore {
private final static String TAG = RealmBackupRestore.class.getName();
private Context context;
private Realm realm;
public RealmBackupRestore(Context context) {
realm= Realm.getDefaultInstance();
//this.realm = Realm.getInstance(BaseApplication.realmConfiguration);
this.context = context;
}
public void backup() {
Log.d(TAG, "realm은"+realm);
Log.d(TAG, "Realm.getDefaultInstance();은"+Realm.getDefaultInstance());
File exportRealmFile = null;
File exportRealmPATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.d(TAG, "exportRealmPATH"+exportRealmPATH);
String exportRealmFileName = "aa.realm";
Log.d(TAG, "Realm DB Path = " + realm.getPath());
try {
// create a backup file
exportRealmFile = new File(exportRealmPATH, exportRealmFileName);
// if backup file already exists, delete it
exportRealmFile.delete();
// copy current realm to backup file
realm.writeCopyTo(exportRealmFile);
} catch (IOException e) {
e.printStackTrace();
}
String msg = "File exported to Path: " +Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
Log.d(TAG, msg);
realm.close();
}
public void restore() {
//Restore
File exportRealmPATH = context.getExternalFilesDir(null);
String FileName = "default.realm";
String restoreFilePath = context.getExternalFilesDir(null) + "/" + FileName;
Log.d(TAG, "oldFilePath = " + restoreFilePath);
copyBundledRealmFile(restoreFilePath, FileName);
Log.d(TAG, "Data restore is done");
}
private String copyBundledRealmFile(String oldFilePath, String outFileName) {
try {
File file = new File(context.getFilesDir(), outFileName);
Log.d(TAG, "context.getFilesDir() = " + context.getFilesDir().toString());
FileOutputStream outputStream = new FileOutputStream(file);
FileInputStream inputStream = new FileInputStream(new File(oldFilePath));
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, bytesRead);
}
outputStream.close();
return file.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String dbPath() {
return realm.getPath();
}
}

ArrayIndexOutOfBoundsException error when writing to a tag

I followed a tutorial on how to write a NDEF message to a tag. and now when I run it. it detects the tag and when I press the button to write the message and the app crashes. it gives me JAVA.LANG.ArrayIndexOutOfBoundsException can someone please help me on what I'm doing wrong.
this is the error I see in logcat.
any help is appreciated.
Here is the code:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class WriteMessage extends Activity {
NfcAdapter adapter;
PendingIntent pendingIntent;
IntentFilter writeTagFilters[];
boolean writeMode;
Tag myTag;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_message);
ctx=this;
Button WriteTag = (Button) findViewById (R.id.WriteTag);
final TextView Message = (TextView) findViewById (R.id.MessageBox);
WriteTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(myTag==null){
Toast.makeText(ctx, "Error_detected", Toast.LENGTH_LONG).show();
}else{
write(Message.getText().toString(), myTag);
Toast.makeText(ctx, "Ok_Writing", Toast.LENGTH_LONG).show();
}
}catch(IOException e){
Toast.makeText(ctx, "Error_Writing", Toast.LENGTH_LONG).show();
e.printStackTrace();
//} catch(FormatException e){
e.printStackTrace();
} catch (FormatException e) {
// TODO Auto-generated catch block
Toast.makeText(ctx, "Error_Writing", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
adapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent (this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter (NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] {tagDetected };
}
private void write(String text, Tag myTag)throws IOException, FormatException {
NdefRecord[] records = {createRecord(text)};
NdefMessage message = new NdefMessage(records);
Ndef ndef = Ndef.get(myTag);
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
}
private NdefRecord createRecord (String text ) throws UnsupportedEncodingException {
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] payload = new byte [1+ langLength + textLength ];
payload[0] = (byte) langLength;
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(langBytes, 0, payload, 1 + langLength, textLength);
NdefRecord recordNFC = new NdefRecord (NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
return recordNFC;
}
#Override
protected void onNewIntent(Intent intent){
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(this, "ok_detection" + myTag.toString(), Toast.LENGTH_LONG ).show();
}
}
#Override
public void onPause(){
super.onPause();
WriteModeOff();
}
#Override
public void onResume(){
super.onResume();
WriteModeOn();
}
private void WriteModeOn(){
writeMode = true;
adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
private void WriteModeOff(){
writeMode = false;
adapter.disableForegroundDispatch(this);
}
}
Looks like createRecord() is copying langBytes into payload twice instead of copying textBytes, but with the length of textBytes. If textBytes is longer than langBytes, it won't find enough data to copy from the source.
See the documentation on arraycopy.

MediaRecorder-recording video using mediarecorder

iam using mediarecorder to record video in android application. I will start and stop recording video multiple times i will start recording on Action_down and stop on Action_up this is going on well and iam able to store and play video file in mobile .
my problem is that since i have to start and stop recording video multiple times i can't use single output file becuase everytime it will get over written so everytime iam passing new file name and iam appending that to one outputfile everytime.iam getting every individual file and final outputfile in mobile but final file is having only what i have recorded for the first time because from second tab if see the file.mp4.length()is zero why it is ? anyone please try to help me. my code is as follows
package com.example.longtouch;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.rtp.AudioGroup;
import android.net.rtp.AudioStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Files;
import android.provider.MediaStore.Video;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity implements OnTouchListener{
int i=1;
File outputFile;
File f1;
File f2;
MediaRecorder mediaRecorder;
ThreadProgress mThreadProgress;
ThreadProgress2 mThreadProgress2;
public int eventAction;
Handler handler;
Handler mHandler;
Button myButton;
FrameLayout myCameraPreview;
Button submit;
Button submit1;
LinearLayout ll;
ProgressBar progressBar;
int progressStatus=0;
MyCameraSurfaceView myCameraSurfaceView;
Camera myCamera;
boolean recording;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recording=false;
myButton=(Button)findViewById(R.id.button_capture);
submit=(Button)findViewById(R.id.submit);
submit1=(Button)findViewById(R.id.submit1);
progressBar=(ProgressBar)findViewById(R.id.progress_bar);
progressBar.setMax(10000);
myCamera = getCameraInstance();
if(myCamera == null){
Toast.makeText(MainActivity.this,
"Fail to get Camera",
Toast.LENGTH_LONG).show();
}
// else
// myCamera.unlock();
myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
myCameraPreview=(FrameLayout)findViewById(R.id.camera_preview);
myCameraPreview.addView(myCameraSurfaceView);
ll=(LinearLayout)findViewById(R.id.ll);
myCameraPreview.setOnTouchListener(this);
outputFile=new File("/sdcard/myvideo.mp4");
if(outputFile.exists()){
outputFile.delete();
outputFile=new File("/sdcard/myvideo.mp4");
try {
outputFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
try {
outputFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
f1=new File("/sdcard/myvideo1.mp4");
if(f1.exists()){
f1.delete();
f1=new File("/sdcard/myvideo1.mp4");
try{
f1.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
else{
try{
f1.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
f2=new File("/sdcard/myvideo2.mp4");
if(f2.exists()){
f2.delete();
f2=new File("/sdcard/myvideo2.mp4");
try{
f2.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
else{
try{
f2.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
}
/* public int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}*/
private Camera getCameraInstance(){
// TODO Auto-generated method stub
Camera c = null;
try {
/* int index = getFrontCameraId();
if (index != -1)
c = Camera.open(index);*/
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public void submit(View v){
// stop recording and release camera
// mediaRecorder.stop(); // stop the recording
// releaseMediaRecorder(); // release the MediaRecorder object
Log.d("outputFile",""+f1.length());
progressStatus=progressBar.getProgress();
//Exit after saved
// finish();
myButton.setText("capture");
recording=false;
submit.setVisibility(View.GONE);
}
public void submit1(View v){
// stop recording and release camera
// mediaRecorder.stop(); // stop the recording
// releaseMediaRecorder(); // release the MediaRecorder object
progressBar.setProgress(0);
progressStatus=0;
//Exit after saved
// finish();
myButton.setText("capture");
recording=false;
submit1.setVisibility(View.GONE);
}
public void display(View v){
Intent i=new Intent(this,VideoPlayer.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public boolean onTouch(View arg0, final MotionEvent event) {
// TODO Auto-generated method stub
eventAction=event.getAction();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
{
i=i+1;
Toast.makeText(getApplicationContext(),"action_down",Toast.LENGTH_SHORT).show();
//releaseCamera();
if(!prepareMediaRecorder()){
Toast.makeText(MainActivity.this,
"Fail in prepareMediaRecorder()!\n - Ended -",Toast.LENGTH_LONG).show();
finish();
}
progressBar.setProgress(progressStatus);
myButton.setText("STOP");
try{
mediaRecorder.start();
}
catch(Exception e){
e.printStackTrace();
Log.d("vd","exception at start method");
}
if(f1.exists()){
long l=f1.length();
Log.d("start","started"+l);
}
if(f2.exists()){
long m=f2.length();
Log.d("start","started"+m);
}
recording = true;
if(progressBar.getProgress()>=5000){
mThreadProgress2=new ThreadProgress2();
mThreadProgress2.start();
}
mHandler = new Handler(new Callback() {
public boolean handleMessage(final Message msg) {
runOnUiThread(new Runnable() {
public void run() {
if( event.getAction()!=MotionEvent.ACTION_UP){
progressBar.setProgress(msg.arg1);
}
if(progressBar.getProgress()==10000){
Log.d("unicorn","1000");
submit1.setVisibility(View.VISIBLE);
}
}
});
return false;
}
});
mThreadProgress=new ThreadProgress();
mThreadProgress.start();
handler = new Handler(new Callback() {
public boolean handleMessage(final Message msg) {
runOnUiThread(new Runnable() {
public void run() {
if( event.getAction()!=MotionEvent.ACTION_UP)
progressBar.setProgress(msg.arg1);
if(progressBar.getProgress()==5000){
submit.setVisibility(View.VISIBLE);
}
}
});
return false;
}
});
return true;
}
case MotionEvent.ACTION_UP:
{ // nothing to do
Toast.makeText(getApplicationContext(),"action_up",Toast.LENGTH_SHORT).show();
myButton.setText("capture");
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
try {
myCamera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Exit after saved
// finish();
recording=false;
progressStatus=progressBar.getProgress();
if(i%2==0){
long len=f1.length();
Log.d("length",""+f1.getPath()+len);
Combine1 c1=new Combine1();
c1.start();
}
else{
long len=f2.length();
Log.d("length",""+f2.getPath()+len);
Combine2 c2=new Combine2();
c2.start();
}
break;
}
default:
return false;
}
return true;
}
private boolean prepareMediaRecorder(){
// myCamera = getCameraInstance();
mediaRecorder = new MediaRecorder();
myCamera.stopPreview();
myCamera.unlock();
mediaRecorder.setCamera(myCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// mediaRecorder.setVideoSize(400,400);
if(i%2==0){
Log.d("outputfile",""+f1.getPath()+f1.length());
mediaRecorder.setOutputFile(f1.getPath());
Log.d("outputfile",""+f1.getPath()+f1.length());
}
else{
Log.d("outputfile",""+f2.getPath()+f2.length());
mediaRecorder.setOutputFile(f2.getPath());
Log.d("outputfile",""+f2.getPath()+f2.length());
}
mediaRecorder.setMaxDuration(10000); // Set max duration 10 sec.
mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
// mediaRecorder.setOnInfoListener(this);
mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d("prepare","illegalstateexception");
e.printStackTrace();
releaseMediaRecorder();
Toast.makeText(getApplicationContext(),"illegal state exception",Toast.LENGTH_SHORT).show();
return false;
} catch (IOException e) {
Log.d("prepare","ioexception");
e.printStackTrace();
releaseMediaRecorder();
Toast.makeText(getApplicationContext(),"IOexception",Toast.LENGTH_SHORT).show();
return false;
}
Log.d("after prepare","after prepare f1"+f1.length());
Log.d("after prepare","after prepare f2"+f2.length());
return true;
}
public void combine(String file){
Log.d("combine","combining"+file);
try{
File inputFile=new File(file);
FileInputStream fis=new FileInputStream(inputFile);
long inputlen=inputFile.length();
Log.d("combine","lengthbefore write"+inputlen);
File outputFile = new File("/sdcard/myvideo.mp4");
FileOutputStream fos = new FileOutputStream(outputFile,true);
byte fileContent[]= new byte[(int)inputFile.length()];
fis.read(fileContent);
long len=outputFile.length();
Log.d("combine","lenth"+len);
fos.write(fileContent);
fis.close();
fos.close();
inputlen=inputFile.length();
len=outputFile.length();
Log.d("combine","inputlength"+inputlen);
Log.d("combine","lenth"+len);
/* File f= new File(file);
boolean deleted = f.delete();
if(deleted){
Log.d("combine","deleted"+file);
} */
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
// myCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (myCamera != null){
myCamera.release(); // release the camera for other applications
myCamera = null;
}
}
public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder holder, int format, int weight,
int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// make any resize, rotate or reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
public class ThreadProgress extends Thread implements Runnable {
int progressValue=progressStatus;
public void run() {
while( progressBar.getProgress()<5000 && eventAction!=MotionEvent.ACTION_UP ) {
Log.d("unicorn","in while loop"+progressValue);
progressValue++;
Message message = new Message();
message.arg1 = progressValue;
if(progressValue<=5000 && eventAction!=MotionEvent.ACTION_UP)
handler.sendMessage(message);
}
}
}
public class ThreadProgress2 extends Thread implements Runnable {
int progressValue=progressStatus;
#Override
public void run() {
while( progressBar.getProgress()<10000 && eventAction!=MotionEvent.ACTION_UP ) {
// try{
Log.d("unicorn2","in while loop"+progressValue);
progressValue++;
Message message = new Message();
message.arg1 = progressValue;
if(progressValue<=10000 && eventAction!=MotionEvent.ACTION_UP)
mHandler.sendMessage(message);
//Thread.sleep(1000);
//} catch (InterruptedException e){
// e.printStackTrace();
// break;
// }
}
}
}
public class Combine1 extends Thread implements Runnable{
public void run(){
try{
int c;
FileInputStream fin=new FileInputStream(f1);
FileOutputStream fout=new FileOutputStream(outputFile,true);
long len1=f1.length();
Log.d("length","myvideo1.mp4"+len1);
long len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
while((c=fin.read())!=-1){
fout.write(c);
}
len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
fin.close();
fout.flush();
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public class Combine2 extends Thread implements Runnable{
public void run(){
try{
int j=0;
FileInputStream fin=new FileInputStream(f2);
FileOutputStream fout=new FileOutputStream(outputFile,true);
long len1=f2.length();
Log.d("length","myvideo2.mp4"+len1);
long len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
while((j=fin.read())!=-1){
fout.write(j);
}
len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
fin.close();
fout.flush();
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
In order to combine multiple video files you should use mp4parser library : https://mp4parser.googlecode.com/svn/trunk/examples/src/main/java/com/googlecode/mp4parser/AppendExample.java

Resources