Android, Developpement
Android envoyer un fichier sur un serveur avec un port TCP
Bon là il faut un serveur TCP en écoute de l’autre côté sur le port 3248…
Read MoreDeveloppement, PHP
PHP petite méthode de validation d’email avec test reverse DNS
Une petite méthode plus simple pour vérifier si un email est valide et existe bien par rapport à son nom de domaine: function checkEmail($email) { // First, we check that there’s one @ symbol, // and that the lengths are right. if (!ereg(« ^[^@]{1,64}@[^@]{1,255}$ », $email)) { // Email invalid because wrong number of characters // in one section or wrong number of @ symbols. return false; } // Split it into sections to make life easier $email_array = explode(« @ », $email); $local_array = explode(« . », $email_array[0]); for ($i = 0; $i < sizeof($local_array); $i++) { if (!ereg(« ^(([A-Za-z0-9!#$%&’*+/=?^_`{|}~-][A-Za-z0-9!#$%& ↪’*+/=?^_`{|}~\.-]{0,63})|(\ »[^(\\|\ »)]{0,62}\ »))$ », $local_array[$i])) { return false; } if(!checkdnsrr($email_array[1], »MX »)&& !checkdnsrr($email_array[1], »A »)){ return false; } }
Read MoreDeveloppement, PHP
PHP OVH API changer les DNS de l’IP principale pour le domaine principal et d’un sous domaine
Ce script va cherche les IDs du domaine principal et d’un sous domaine et à partir de ces IDs modifie l’IP cible… Il vous suffit d’indiquer vos informations d’identifications: $AK = « »; $AS = « »; $CK = « »; Et changer « xxx.xxx.xxx.xxx » par la nouvelle IP cible Et changer « nom-de-domaine.com » par votre nom de domaine biensûr ! <?php # Copyright (c) 2013, OVH SAS. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # #* Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. #* Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. #* Neither the name of OVH SAS nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY OVH SAS AND CONTRIBUTORS « AS IS » AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,…
Read MoreDeveloppement, PHP
PHP envoyer un email avec PHPMailer
Voici comment envoyer un email html avec PHPMailer. $mail = new PHPMailer ( true ); // defaults to using php « mail() »; the true param means it will throw exceptions on errors, which we need to catch $mail->AddReplyTo ( ‘noreply@my.server.com’, ‘Admin Server’ ); $mail->AddAddress ( ‘target_email@client.server.com’ ); $mail->SetFrom ( ‘noreply@my.server.com’, ‘Message’ ); $mail->Subject = ‘Subject’; $body = « YOUR HTML MESSAGE »; // HTML tag $mail->MsgHTML ( $body ); // $mail->Body = $message; $mail->Send (); } catch ( phpmailerException $e ) { $log->error ( « CONTACT -Erreur envoi : » ); $log->error ( $e->getMessage () ); } catch ( Exception $e ) { $log->error ( « CONTACT -Erreur envoi : » ); $log->error ( $e->getMessage () ); } Voilà !
Read MoreDeveloppement, PHP
PHP lire un fichier et effacer la première ligne
Petite méthode pour lire un fichier, récupérer la valeur de la première ligne puis effacer cette ligne avant d’enregistrer le fichier à nouveau. function read_and_delete_first_line($filename) { $file = file ( $filename ); $output = $file [0]; unset ( $file [0] ); file_put_contents ( $filename, $file ); return $output; } $myFirstLineData= read_and_delete_first_line ( « /var/myfile » ); Attention cela ne fonctionne que si l’utilisateur qui appelle cette méthode à les droits en écriture sur le fichier cible « myfile ».
Read MoreDeveloppement, JavaFX
JavaFX envoyer des informations en POST avec BASIC authentication
Envoyer un POST sur une page PHP avec une authentification BASIC: import java.util.ArrayList; import java.util.Locale; import javafx.concurrent.Service; import javafx.concurrent.Task; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class SendInformationsToServer extends Service<Void> { String serverAdress = new ObfuscatedString(new long[] {0x48293BBB503D3EDBL, 0xF64DDCEE66BAE29EL, 0x7788E3D61ADECC17L, 0x5764815B0D4457BAL, 0xDDB97EDA9E2632E1L}).toString(); ///http://my.server.com/ String serverRealm = new ObfuscatedString(new long[] {0xA2761EA86C347E34L, 0xB8043A57A9976A22L, 0xE84223FC32AC309EL, 0x5B806D1BB6502EB4L}).toString(); ///my.server.com String pass = new ObfuscatedString(new long[] {0x62D33FE83DC25EFDL, 0xB767F942869048D8L, 0xF2666902653CE769L}).toString(); String login = new ObfuscatedString(new long[] {0x5EAC65F126BCA127L, 0xBC4D210989A36D0L, 0x42ADC688BE800C2CL}).toString(); @Override protected Task<Void> createTask() { return new Task<Void>() { protected Void call() throws Exception { Locale locale = Locale.getDefault(); String lang = locale.getDisplayLanguage(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(serverRealm, 80), new UsernamePasswordCredentials(login, pass)); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); HttpHost targetHost = new HttpHost(serverRealm, 80, « http »); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); try { HttpPost httppost = new…
Read MoreDeveloppement, JavaFX
JavaFX override tab dans les TextArea pour la navigation clavier
Avec cette méthode l’utilisateur pourra changer de champ avec « tab » même dans la TextArea. Si l’utilisateur fait Alt-Tab il fait bien un tab… myTextArea.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getCode() == KeyCode.TAB) { TextAreaSkin skin = (TextAreaSkin) putShareTextArea.getSkin(); if (skin.getBehavior() instanceof TextAreaBehavior) { TextAreaBehavior behavior = (TextAreaBehavior) skin.getBehavior(); if (event.isControlDown()) { behavior.callAction(« InsertTab »); } else if (event.isShiftDown()) { behavior.callAction(« TraversePrevious »); } else{ behavior.callAction(« TraverseNext »); } event.consume(); } } else if (event.getCode() == KeyCode.ENTER) { TextAreaSkin skin = (TextAreaSkin) putShareTextArea.getSkin(); if (skin.getBehavior() instanceof TextAreaBehavior) { TextAreaBehavior behavior = (TextAreaBehavior) skin.getBehavior(); if (event.isControlDown()) { behavior.callAction(« InsertTab »); } else if (event.isShiftDown()) { behavior.callAction(« TraversePrevious »); } else{ behavior.callAction(« TraverseNext »); } event.consume(); } } } }); Pas si compliqué 🙂
Read MoreDeveloppement, JavaFX
JavaFX simple animation
Une petite méthode pour faire tourner une image indéfiniment sur son axe… public ParallelTransition setParallelTransitionForNode(Node node) { FadeTransition fadeTransition = new FadeTransition(Duration.millis(10000), node); fadeTransition.setFromValue(1.0f); fadeTransition.setToValue(0.0f); fadeTransition.setAutoReverse(true); RotateTransition rotateTransition = new RotateTransition(Duration.seconds(10), node); rotateTransition.setAxis(Rotate.Y_AXIS); rotateTransition.setFromAngle(0); rotateTransition.setToAngle(360); rotateTransition.setAutoReverse(true); ParallelTransition parallelTransition = new ParallelTransition(); parallelTransition.getChildren().addAll( fadeTransition, rotateTransition ); parallelTransition.setCycleCount(Timeline.INDEFINITE); parallelTransition.play(); return parallelTransition; } Avec « ParallelTransition » vous pouvez ajouter toute autre animation à celles déjà positionnées ci-dessus. Après la seule limite est presque l’imagination !
Read MoreDeveloppement, JavaFX
Java Http Commons Librairie et authentification basic
Voici une petite méthode qui utilise la libraire « http commons » et qui s’authentifie en type « BASIC » sur un serveur web qui a un « .htaccess » pour limiter l’accès. private boolean getInfos() { boolean hasentries = false; try { HttpHost targetHost = new HttpHost(« server.name », 80, « http »); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(« login », « password »)); AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context final HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(new HttpGet(serverAdress + « get.php »), context); HttpEntity responseEntity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); String entityContents = EntityUtils.toString(responseEntity); if (entityContents.contains(« # »)) { hasentries = true; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return hasentries; } La méthode appelle le fichier get.php et si il y a des entrées retourne « true » A vous de jouer !
Read MoreAndroid, Developpement
Android download de fichier
Télécharger un fichier à partir d’une URL, on vérifie via MD5 que le fichier téléchargé est bien similaire à celui du départ (sinon on utilise celui en local du dossier « raw »: xmlfile.xml): public boolean downloadFile(final String path) { try { URL url = new URL(path); //On récupère le MD5 du fichier à télécharger pour le comaprer au fichier qui va être /// téléchargé juste après String md5online = new String(Hex.encodeHex(DigestUtils.md5(path))); Log.d(« MD5ONLINE », md5online); URLConnection ucon = url.openConnection(); ucon.setReadTimeout(5000); ucon.setConnectTimeout(10000); InputStream is = ucon.getInputStream(); BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); ///L’emplacement de ce fichier est dans la partie « privée » de l’application Android File file = new File(MainActivity.this.getDir(« filesdir », Context.MODE_PRIVATE) + « /xmlfile.xml »); ///SI le fichier existait on le supprime if (file.exists()) { file.delete(); System.out.println(« file deleted !!!!!!!!!!!!!!!!!! »); } //On crée le fichier file.createNewFile(); ///Et on écrit le résultat du parsing du fichier distant dans un fichier local FileOutputStream outStream = new FileOutputStream(file); byte[] buff = new byte[5 * 1024]; int len; while ((len = inStream.read(buff)) != -1) { outStream.write(buff, 0, len); } outStream.flush(); outStream.close(); inStream.close(); String md5download = new String(Hex.encodeHex(DigestUtils.md5(file.getAbsolutePath()))); Log.d(« MD5DOWN », md5download); ///SI le fichier télécgharger est différents du fichier reçu on utilise le fichier en local /// car il y a eût…
Read MoreAndroid, Developpement
Android empêcher la veille
Tout simplement: getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Done !
Read MoreAndroid, Developpement
Android récupérer l’adresse IP
On va faire un peu (beaucoup) de formatage de résultat: public String getIpAddr() { WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ip = wifiInfo.getIpAddress(); String ipString = String.format(« %d.%d.%d.%d »,(ip & 0xff), (ip >> 8 & 0xff),(ip >> 16 & 0xff),(ip >> 24 & 0xff)); return ipString; } Done !
Read MoreAndroid, Developpement
Android supprimer un dossier plein de fichiers
Assez simplement: public void DeleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles()) { DeleteRecursive(child); Log.d(« File deleted: « , « »+child.getAbsolutePath()); } fileOrDirectory.delete(); } Done !
Read MoreAndroid, Developpement
Android nombre de jours entre deux dates
Un peu moins simplement :-): public String getDateDiffString(Date dateOne, Date dateTwo) { long timeOne = dateOne.getTime(); long timeTwo = dateTwo.getTime(); long oneDay = 1000 * 60 * 60 * 24; long delta = (timeTwo – timeOne) / oneDay; if (delta > 0) { return « »+delta; } else { delta *= -1; return « »+delta; } } Done !
Read MoreAndroid, Developpement
Android tester si c’est un téléphone ou une tablette
Tout simplement: private boolean hasPhoneAbility() { TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if(telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) return false; return true; } Done !
Read MoreAndroid, Developpement
Android tester si il y a une connectivité réseau
Tout simplement: private static boolean isConnected(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = null; if (connectivityManager != null) { networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); } return networkInfo == null ? false : networkInfo.isConnected(); } Done !
Read MoreAndroid, Developpement
Android Dialog Custom Iphone Style
Une première classe « CustomizeDialog »: import android.app.Dialog; import android.content.Context; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.TextView; public class CustomizeDialog extends Dialog implements OnClickListener { Button okButton; Context mContext; TextView mTitle = null; TextView mMessage = null; View v = null; public CustomizeDialog(Context context) { super(context); mContext = context; /** ‘Window.FEATURE_NO_TITLE’ – Used to hide the mTitle */ requestWindowFeature(Window.FEATURE_NO_TITLE); /** Design the dialog in main.xml file */ setContentView(R.layout.custom_toast); v = getWindow().getDecorView(); v.setBackgroundResource(android.R.color.transparent); mTitle = (TextView) findViewById(R.id.dialogTitle); mMessage = (TextView) findViewById(R.id.dialogMessage); } @Override public void setTitle(CharSequence title) { super.setTitle(title); mTitle.setText(title); } @Override public void setTitle(int titleId) { super.setTitle(titleId); mTitle.setText(mContext.getResources().getString(titleId)); } /** * Set the message text for this dialog’s window. * * @param message * – The new message to display in the title. */ public void setMessage(CharSequence message) { mMessage.setText(message); mMessage.setMovementMethod(ScrollingMovementMethod.getInstance()); } /** * Set the message text for this dialog’s window. The text is retrieved from the resources with the supplied * identifier. * * @param messageId * – the message’s text resource identifier <br> * @see <b>Note : if resourceID wrong application may get crash.</b><br> * Exception has not handle. */ public void setMessage(int messageId) { mMessage.setText(mContext.getResources().getString(messageId)); mMessage.setMovementMethod(ScrollingMovementMethod.getInstance()); } @Override public void onClick(View arg0) {…
Read MoreAndroid, Developpement
Android trouver si une application est installée
Une simple méthode pour voir si une application est installée (via le nom de package x.x.x): public boolean isProAppPresent(Context context){ try { PackageInfo info = context.getPackageManager().getPackageInfo(« my.package.android », PackageManager.GET_META_DATA); Log.d(« TAG », « Pro app is installed: » + info.applicationInfo.name); return context.getPackageManager().checkSignatures(« my.package.android.free », « my.package.android ») == PackageManager.SIGNATURE_MATCH; } catch (NameNotFoundException e) { return false; } } Done !
Read MoreAndroid, Developpement
Envoyer des données en POST avec Android hors du main UI
Voici une méthode pour faire un POST sur une page PHP sans bloquer le main UI Thread: Une AsyncTask: private class insertInAppBillingOnline extends AsyncTask<String, Void, String> { final String URL_STRING = « https://mywebsite.com/myphp.php »; /* => HttpResponse response; @Override protected String doInBackground(String… urls) { SimpleDateFormat sdf = new SimpleDateFormat(« yyyy/MM/dd HH:mm:ss »); String currentDateandTime = sdf.format(new Date()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair(« date », currentDateandTime)); nameValuePairs.add(new BasicNameValuePair(« deviceid », Secure.getString(getContentResolver(), Secure.ANDROID_ID))); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(URL_STRING); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { } } Exécution: insertInAppBillingOnline insert = new insertInAppBillingOnline(); insert.execute(); Et le code PHP qui va récupérer les valeurs POST et insérer le tout dans une BDD: $date = $_POST[‘date’]; $deviceid= $_POST[‘deviceid’]; $db_host= »127.0.0.1″; $db_user= »rootuser »; $db_pass= »password »; $db_name= »name »; $con = mysql_connect($db_host, $db_user, $db_pass) mysql_select_db($db_name, $con); mysql_query(« INSERT INTO mytable(DATE, DEVICEID) VALUES (‘$date’, ‘$deviceid’) »); mysql_close($con); Voilà !
Read MoreAndroid, Developpement
Android AsynTask récupérer valeur de la méthode « onPostExecute() »
Voici l’AsynTask qui retourne un boolean: private class verifyInAppBillingOnline extends AsyncTask<Void, Void, Boolean> { Boolean ispremium = false; private verifyInAppBillingOnlineInterface mListener; public verifyInAppBillingOnline(Context context, verifyInAppBillingOnlineInterface mListener){ this.mListener = mListener; } @Override protected Boolean doInBackground(Void… urls) { return ispremium; } @Override protected void onPostExecute(Boolean result) { result = ispremium; } } On crée une interface qui sera exécutée sur le onPostExecute(): public interface verifyInAppBillingOnlineInterface { public void verifyInAppBillingOnlineResult(boolean result); } Puis on déclare l’AsyncTask et on récupère la méthode de l’interface: verifyInAppBillingOnline task = new verifyInAppBillingOnline(Activity.this,new verifyInAppBillingOnlineInterface() { @Override public void verifyInAppBillingOnlineResult(boolean result) { Log.d(« INAPP result », « »+result); if (result == true) { Log.d(« INAPP result », « OK »); ispremium = result; } else { Log.d(« INAPP result », « KO »); ispremium = result; } } }); task.execute(); Voilà !
Read More