static TranslateTextResponse translateText ( String projectId , String location , String text , String sourceLanguageCode , String targetLanguageCode ) { try ( TranslationServiceClient translationServiceClient = TranslationServiceClient . create ( ) ) { LocationName locationName = LocationName . newBuilder ( ) . setProject ( projectId ) . setLocation ( location ) . build ( ) ; TranslateTextRequest translateTextRequest = TranslateTextRequest . newBuilder ( ) . setParent ( locationName . toString ( ) ) . setMimeType ( "text/plain" ) . setSourceLanguageCode ( sourceLanguageCode ) . setTargetLanguageCode ( targetLanguageCode ) . addContents ( text ) . build ( ) ; // Call the API TranslateTextResponse response = translationServiceClient . translateText ( translateTextRequest ) ; System . out . format ( "Translated Text: %s" , response . getTranslationsList ( ) . get ( 0 ) . getTranslatedText ( ) ) ; return response ; } catch ( Exception e ) { throw new RuntimeException ( "Couldn't create client." , e ) ; } }
Translates a given text to a target language .